Problem 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:
\[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, \ldots\]
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
A Solution
Let \(F_1, F_2, \ldots\) denote the (non-standard) Fibonnaci sequence with \(F_1 = 1\) and \(F_2 = 2\). Then, for each integer \(n \geq 2\), \[F_{n+1} = F_{n-1} + F_n.\]
We create a vector fibs
of Fibonacci numbers (starting from 1 and 2) less than 4 million.
fibs <- c(1, 2)
n <- 2 # length of fibs
x <- fibs[1] + fibs[2] # value of the next Fibonacci number
while (x < 4e6) {
n <- n + 1
fibs <- c(fibs, x)
x <- fibs[n-1] + fibs[n]
}
fibs
## [1] 1 2 3 5 8 13 21 34 55
## [10] 89 144 233 377 610 987 1597 2584 4181
## [19] 6765 10946 17711 28657 46368 75025 121393 196418 317811
## [28] 514229 832040 1346269 2178309 3524578
We sum all the numbers in fibs
that are even to get the result.
s <- sum(fibs[fibs %% 2 == 0])
s
## [1] 4613732