#2: Even Fibonacci numbers
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:
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Python
ans = 2
terms = [1, 2, 3]
max = 4000000
while terms[2] <= max:
terms[0:2] = terms[1:3]
terms[2] = sum(terms[0:2])
if (terms[2] % 2 == 0) and (terms[2] <= max):
ans += terms[2]
print(ans)
## 4613732
R
x <- 1:2
max <- 4000000
while (tail(x, 1) < max) {
x <- c(x, sum(tail(x, 2)))
}
sum(x[x %% 2 == 0 & x <= max])
## [1] 4613732