Finding Even Fibonacci Numbers Below a Threshold

The Problem

It’s time for the second Project Euler problem set! The problem requires finding the even Fibonacci Sequence numbers below 4,000,000. I calculated the sum of the Fibonacci sequence using this formula:

 \sum\limits_{1}^{N} N + (N-1)

Technically, the formula for the sequence is slightly different, but the above formula gives you an idea of how to think about summing the sequence.

The Method

Loops are a coding fundamental, but not one that I am completely comfortable with yet. Part of my reasoning for using Project Euler is to improve my comfort with loops.

I start by clearing the workspace and initializing my variables for calculation. I then use a while loop. The loop continues until either the entry size exceeds the limit, or the vector length exceeds that same limit. I append the vector on each loop and increment the counter for the next loop. I then show the vector (x) for visual inspection.

This vector contains the entire Fibonacci Sequence up to the limit of 4 million, not merely the even entries, so I have to clean it up. I do this by creating a logical vector where each entry of the vector x is divided by two. If the modulo is 0, it returns TRUE, else FALSE. I then feed this vector back into x to create another vector, which I then sum to find the answer.

Ideally, I’d like to include the operation checking for even entries inside the while loop. However, my attempts resulted in a non-functioning code-chunk. The version I described above ran in 0.1799641 seconds between clearing the variables and finding the result. The version with an extra if statement ran for over a minute and still hadn’t completed when I aborted it.

I am open to suggestions to improve the code. Please comment below if you have an idea for optimization!

You can find the R file here. The code below is the minimum required to run as described above:

rm()
N <- 4e6
x <- c(1, 2)
i <- 2

while (x[i] < N) {
  if (x[i]+x[i-1] > N) break
  x <- c(x, x[i]+x[i-1])
  i <- i+1
}

x

e <- x%%2 == 0
a <- x[e]

sum(a)