Project Euler — problem 2
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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.
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().
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.