Problem 2-Even Fibonacci numbers

There are tons of algorithms for generating the Fibonacci numbers, such as the recursive way which is quite elegant. However, for this problem only, we don’t need to generate the whole sequence.

Suppose we have already know what a_{n-1} and a_{n} are, it’s easy to calculate a_{n+1} = a_{n-1}+a_{n}. Then we check whether a_{n+1} is even or not. If it’s even, we sum the number to the final result. Next we update a_{n-1} = a_{n} and a_{n} = a_{n+1}, and move to the next item in Fibonacci sequence.

The virtue of this method is to (supposedly) reduce the memory usage. Although there are only 34 Fibonacci numbers under 4 million, and I don’t see a particular reason for avoiding generating all these numbers.

And for your reference, here is the list of first 300 Fibonacci numbers: The first 300 Fibonacci numbers, factored

upper_limit = 4e6
old_fib1 = 1
old_fib2 = 1
new_fib = 0
sum = 2
while(new_fib < upper_limit){
    new_fib = old_fib1 + old_fib2
    if(new_fib %% 2 == 0){
      sum = sum + new_fib
    }
    old_fib1 = old_fib2
    old_fib2 = new_fib
}

Disclaimer (and some initial thoughts)

MAKE SURE YOU HAVE PUT ALL YOUR EFFORTS TO SOLVE THE PROBLEMS BEFORE CHECKING MY POSTS!

In general, it’s not encouraged by the Project Euler to post solutions outside the official forum. However, the R users are hugely underrepresented in Project Euler, and I feel like it would be a good idea to record my thoughts on solving these problems using R (might also include some Python if time allowed).

For people who have never heard of R, it is one of the most important, if not THE most important, tools of modern statisticians, and it’s widely implemented in both academia and industry with a very active community.

My goal is to solve these numerical problems with R as a way to improve my R programming skills. As a PhD student in statistics, I am by no means a master of algorithm. My solutions would be tedious and clumsy, and R by its nature slow and not so elegant. I will try to solve these problems in a clear and straightforward way rather than playing with those tricks. I do this for several reasons. First, many of the tricks are out of the bound of my knowledge. Second, as a (future) statistician, my job is not about writing the codes that are ready to use. So I feel it would not be necessary for me to put too much attention on these tricks.

All problems are listed on Project Euler’s website https://projecteuler.net