# Fibonacci number with 1000 digits, Euler Problem 25

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.

## 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:

$F_n = F_{n-1} + F_{n-2}$, where $F_1 = 1$ and $F_2 = 1$. The 12th term, $F_{12}$, 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 &lt;- 1
fib &lt;- 1
while (nchar(as.character(fib)) &lt; 1000) {
fib &lt;- fibnum(n) # Determine next Fibonacci number
n &lt;- n + 1
}
```

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. This code is much slower than the GMP library but it was fun to develop.

```fib &lt;- 1 # First Fibonaci number
cur &lt;- 1 # Current number in sequence
pre &lt;- 1 # Previous number in sequence
index &lt;- 2
while (nchar(fib) &lt; 1000) {
fib &lt;- big.add(cur, pre) # Determine next Fibonacci number
pre &lt;- cur
cur &lt;- fib
index &lt;- index + 1
}