Euler Problem 2: Even Fibonacci Numbers

December 7, 2016
By

(This article was first published on The Devil is in the Data, and kindly contributed to R-bloggers)

Euler Problem 2 Definition

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, \ldots

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Solution

The code generates Fibonacci numbers until it reaches the value of four million. The code then sums the even numbers in the sequence.

fib <- c(1, 2)  #Define first two numbers
while (max(fib) < 4e+06) {
    # Generate Fibonacci numbers until limit is reached
    len <- length(fib)
    fib <- c(fib, fib[len - 1] + fib[len])
}
answer <- sum(fib[fib%%2 == 0])

A range of packages exists that generate Fibonacci numbers. The gmp package for Multiple Precision Arithmetic and the numbers package supplies functions to calculate the nth Fibonacci number. This package is also able to work with very large numbers.

library(gmp)
i <- 1
answer <- 0
fib <- fibnum(1)
while (fibnum(i) <= 4e6) {
    fib <- fibnum(i)
    if (fib%%2==0) answer <- answer + fib
    i <- i + 1
}
print(answer)

Fibonacci Numbers as a magic trick

Fibonacci numbers describe many natural processes and can also be used to create magic tricks. The Missing Square Puzzle is based on this principle.

By Trekky0623 at English Wikipedia (Transferred from en.wikipedia to Commons.) [Public domain], via Wikimedia Commons

By Trekky0623 at English Wikipedia (Transferred from en.wikipedia to Commons.) [Public domain], via Wikimedia Commons

The post Euler Problem 2: Even Fibonacci Numbers appeared first on The Devil is in the Data.

To leave a comment for the author, please follow the link and comment on their blog: The Devil is in the Data.

R-bloggers.com 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...

Comments are closed.

Search R-bloggers


Sponsors

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)