# Project Euler — problem 2

May 21, 2012
By

(This article was first published on Tony's bubble universe » R, and kindly contributed to R-bloggers)

Almost my time for bed. Just write a quick solution on the second problem of Project Euler. Here it is.

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, … By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

The solution is straightforward: firstly generate the Fibonacci sequence, then calculate the sum of even numbers.

?View Code RSPLUS
 1 2 3 4 5 6 7 8 9 10 11 12 13 14  fibonacci <- numeric() fibonacci[1] <- 1 fibonacci[2] <- 2 i <- 3 repeat { fibonacci[i] <- fibonacci[i-1] + fibonacci[i-2] if (fibonacci[i] > 4e6) break i <- i + 1 } # calculate the sum fibonacci <- fibonacci[-length(fibonacci)] # remove the last term flag <- fibonacci %% 2 == 0 # find the indexes of even numbers result <- sum(fibonacci[flag]) cat("The result is:", result, "\n")

I miscalculated twice on this problem. The first was a misunderstanding to calculate the sum the even-indexed terms; the second was just a bug. I guess I was sleepy. I believe there must be some brilliant mathematical ways to solve it. I’ll read the forum later.
Functions used: repeat, break (two flow control commands) and length(), sum().

To leave a comment for the author, please follow the link and comment on his blog: Tony's bubble universe » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , ,