Project Euler — problem 25
[This article was first published on Tony's bubble universe » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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 = Fn1 + Fn2, 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
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 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.