If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 10000.
# R
get_sum_multiples_below1 <- function(below,multiple_1,multiple_2){
sum <- 0
for(i in 1:(below-1)){
if((i %% multiple_1 == 0)|(i %% multiple_2 == 0)){
sum <- sum + i
}
}
return(sum)
}
t <- Sys.time()
get_sum_multiples_below1(10000,3,5)
## [1] 23331668
Sys.time() - t
## Time difference of 0.004268169 secsBy listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
# R
is_nb_prime <- function(nb){
is_prime = TRUE
for(j in 2:(round(sqrt(nb))+1)){
if(nb%%j == 0){
is_prime = FALSE
break
}
}
return(is_prime)
}
nth_prime <- function(nth){
primes = c(2,3)
i = 3
while(length(primes)<nth){
i <- i+1
is_prime = is_nb_prime(i)
if(is_prime == TRUE){
primes = c(primes,i)
}
}
return(primes[nth])
}
t <- Sys.time()
nth_prime(10001)
## [1] 104743
Sys.time() - t
## Time difference of 0.451252 secsYou are given the following information, but you may prefer to do some research for yourself.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
get_sundays <- function(year,first_sunday){
# Get number of days per month
if((year %% 100 != 0 & year%%4 == 0) | year %% 400 == 0){
month_length = c(31,29,31,30,31,30,31,31,30,31,30,31)
} else {
month_length = c(31,28,31,30,31,30,31,31,30,31,30,31)
}
# total number of days
nb_days = sum(month_length)
# position of the first days of the month
cumsum_year = cumsum(month_length)-month_length+1
# position of all sundays
sundays = seq(first_sunday,nb_days,7)
# get first sunday of the following year
next_sunday_position = sundays[length(sundays)] - nb_days + 7
nb_sundays_first = length(which(sundays %in% cumsum_year))
return(c(next_sunday_position,nb_sundays_first))
}
t = Sys.time()
# Intialize with 1900, we know that the first sunday is the 7th.
year_result = get_sundays(1900,7)
# compute the sum for each year
nb_sundays = 0
for(i in seq(1901,2000)){
next_sunday = year_result[1]
year_result = get_sundays(i,next_sunday)
nb_sundays = nb_sundays + year_result[2]
}
Sys.time() - t
## Time difference of 0.03932309 secs
# results
nb_sundays
## [1] 171