Categories
Coding Project Euler R

Project Euler Problem #2 (R)

Here is a solution for Project Euler’s Problem #2 in R, which is stated as:

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, …

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

Firstly ,we will define a function to calculate the Fibonacci numbers below N, where N in this case is 4*10^6:

[code lang=”R”]
fib < – function(n) {
x <- c(length=10)
x[1] <- 1; x[2] <- 2
for (i in 3:n) {
y <- x[i-1]+x[i-2];
if (y > n){ break }
else { x[i] < – y }
}
x
}
[/code]

Next, we just calculate the sum of the even-valued problems, in a similar manner to the way we solved problem #1:

[code lang=”R”]
f < – fib(4E6)
sum(f[f %% 2 ==0])
[/code]