Euler 2

The second Project Euler problem.

Given the Fibonacci sequence, calculate all terms below 4 million. What is the sum of the even terms?

We are going to use the library “numbers” a lot!
It includes a function, that allows us to generate the Fibonacci-sequence. But how many terms should we get?
By inspection we find that the 34th term is:

library(numbers)
fibonacci(34)
## [1] 5702887

Therefore we only need the 33 first terms:

(f <- fibonacci(33, sequence = TRUE))
##  [1]       1       1       2       3       5       8      13      21
##  [9]      34      55      89     144     233     377     610     987
## [17]    1597    2584    4181    6765   10946   17711   28657   46368
## [25]   75025  121393  196418  317811  514229  832040 1346269 2178309
## [33] 3524578

We only have to sum the even terms:

sum(f[!f%%2])
## [1] 4613732

Lets split that up a bit. %% i modulus. It returns what is “left” in the division.
4%%2 returns 0, because there is no remainder – because 4 is an equal number.
When we do that on all the terms in the sequence, we get:

f%%2
##  [1] 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0

0 for the equal terms, 1 for the unequal terms.
0 is equivalent to FALSE, and 1 to TRUE.
And ! negates the logical value:

!f%%2
##  [1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE
## [12]  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE
## [23] FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE

Compare that with the original sequence – now the value is FALSE for the unequal numbers, and true for the equal.
We can use that to pick out the equal terms in the sequence:

f[!f%%2]
##  [1]       2       8      34     144     610    2584   10946   46368
##  [9]  196418  832040 3524578

And then it is simple enough to just sum them:

sum(f[!f%%2])
## [1] Censored

Lessons learned:
1. You should always save your Euler solutions, otherwise you will have to reconstruct them when you decide to put them all on your website three years later.
2. Numbers is a really usefull library.