R编程题目练习1
Multiples of 3 and 5
Problem 1
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 1000.
answer:
n <- c()
n[1] <- 0
for (i in 1:999){
if (i%%3==0){
n <- n+i
}
else if(i%%3!=0&i%%5==0){
n <- n+i
}
}
cat("The answer is:", n)
The answer is: 233168
Even Fibonacci numbers
Problem 2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.、
answer:
f <- c()
f[1] <- 1
f[2] <- 2
i <- 3
repeat{
f[i] <- f[i-2]+f[i-1]
if(f[i]>4000000)break
i <- i+1
}
f <- f[-length(f)]
f_even_index <- f%%2==0
f_even_sum <- sum(f[f_even_index])
cat("The answer is:", f_even_sum,"\n")
The answer is: 4613732