Project Euler — problem 25

January 16, 2013
By

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

Finally, the fog lasting for days went away this morning and the sun comes out. It’s a lovely winter day. After taking a walk after lunch, I feel like doing some math. So, here comes the 25th Euler problem.

The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. What is the first term in the Fibonacci sequence to contain 1000 digits?

Well, it’s a simple Fibonacci problem, which I have solved several times before. The only issue is that I have to deal with big integers. For the reason of convenience, I’m gonna use the helpful “gmp” package, again. Hope nobody minds :p

?View Code RSPLUS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
library(gmp)
first <- as.bigz(1)
second <- as.bigz(1)
third <- first + second
n <- 2
 
while(nchar(as.character(third)) < 1000) {
  n <- n + 1
  third <- first + second
  first <- second
  second <- third
}
 
cat("The result is:", n, "\n")

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

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.

Sponsors

Mango solutions



RStudio homepage



Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training



http://www.eoda.de









ODSC

CRC R books series











Contact us if you wish to help support R-bloggers, and place your banner here.

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)