Large integers in R: Fibonacci number with 1000 digits, Euler Problem 25
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Euler Problem 25 takes us back to the Fibonacci sequence and the problems related to working with very large integers.
The Fibonacci sequence follows a simple mathematical rule but it can create things of great beauty. This pattern occurs quite often in nature, like to nautilus shell shown in the image. The video by Arthur Benjamin at the end of this post illustrates some of the magic of this sequence.
Large Integers in R
By default, numbers with more than 7 digits are shown in scientific notation in R, which reduces the accuracy of the calculation. You can change the precision of large integers with the options function but R struggles with integers with more than 22 digits. This example illustrates this issue.
factorial(24) [1] 6.204484e+23 > options(digits=22) > factorial(24) [1] 620448401733239409999872
However, finding a number of 1000 digits is a problem with using special functions.
Euler Problem 25 Definition
The Fibonacci sequence is defined by the recurrence relation:
, where and . The 12th term, , is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
Proposed Solutions
The first solution uses the GMP library to manage very large integers. This library also contains a function to generate Fibonacci numbers. This solution cycles through the Fibonacci sequence until it finds a number with 1000 digits.
library(gmp) # GNU Multiple Precision Arithmetic Library n <- 1 fib <- 1 while (nchar(as.character(fib)) < 1000) { fib <- fibnum(n) # Determine next Fibonacci number n <- n + 1 } answer <- n print(answer)
This is a very fast solution but my aim is to solve the first 100 Project Euler problems using only base-R code. The big.add function I developed to solve Euler Problem 13.
t <- proc.time() fib <- 1 # First Fibonaci number cur <- 1 # Current number in sequence pre <- 1 # Previous number in sequence index <- 2 while (nchar(fib) < 1000) { fib <- big.add(cur, pre) # Determine next Fibonacci number pre <- cur cur <- fib index <- index + 1 } answer <- index print(answer)
This code is much slower than the GMP library but is was fun to develop.
The Magic of the Fibonacci Numbers
The post Large integers in R: Fibonacci number with 1000 digits, Euler Problem 25 appeared first on The Devil is in the Data.
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.