Project Euler: problem 2

September 16, 2011

(This article was first published on We think therefore we R, and kindly contributed to R-bloggers)

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.

# Inititae a vector x with two values 1 and 2, the starting points for the Fibonacci series 
x <- c(1,2)

# Take an object “i”, with a starting value of 1. 
# This object will be used to as an index for the vector “x”. 
# We continue to add# the (n – 1)th term  and the (n – 2)th term
# to get the nth term. 
# This process continues as long as an element of vector x with 
# index value “i” just crosses the 4,000,000 mark.
i <- 1
while (x[i] < 4000000){i <- i + 1
                        x.index <- length(x)
                        x[x.index + 1] <- x[x.index] + x[x.index – 1]}

# Sum the even values of the Fibonacci series thus obtained
sum(x[x %% 2 == 0])

Answer : 4613732

To leave a comment for the author, please follow the link and comment on their blog: We think therefore we R. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, 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: , , ,

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)