Project Euler 25: Find the first term in the Fibonacci sequence to contain 1000 digits
Project Euler 25 Problem Description
Project Euler 25: 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.
Hence the first 12 terms will be:
F_{1} = 1 F_{2} = 1 F_{3} = 2 F_{4} = 3 F_{5} = 5 F_{6} = 8 |
F_{7} = 13 F_{8} = 21 F_{9} = 34 F_{10} = 55 F_{11} = 89 F_{12} = 144 |
The 12th term, F_{12}, is the first term to contain three digits.
What is the first term in the Fibonacci sequence to contain 1000 digits?
Analysis
Solving this problem simply comes down to knowing Binet’s formula for finding the nth Fibonacci term and using logs to determine its magnitude. This formula takes advantage of Fibonacci terms converging to φF_{n} = F_{n+1}, where φ(Phi) is the Golden Ratio .
Wikipedia shows us that the nth Fibonacci number is , so we define an inequality that we will use to solve for n for the first Fibonacci number that exceeds d digits. In the case of 1000 digits it would be 10^{999} or 1 followed by 999 zeros; a thousand digits:
We want to solve for n to get the Fibonacci term. Remove the fraction from the left side:
Take the log of both sides:
The log(10) is simply 1 and we can easily solve for n:
Use the ceiling function to find the closest integer.
The HackerRank version of this problem requires a program to run thousands of trials for values of d between 2 and 5,000 in a few seconds.
Project Euler 25 Solution
Runs < 0.001 seconds in Python 2.7.Use this link to get the Project Euler 25 Solution Python 2.7 source.
Answer
Slowly swipe from either end beginning with the white vertical bar to get an idea of the starting or ending digits. For less drama, just double click the answer area. The distance between the two bars will give you an idea of the magnitude. Touch devices can tap and hold the center of the box between the two bars and choose define to reveal the answer.Afterthoughts
- Works for number of digits, L > 1
- Did you know that you can use the Fibonacci sequence to convert between miles and kilometers? Just find the miles in the sequence and take the next value in the sequence for an approximate measure in kilometers. For example, 89 miles is approximately 144 kilometers.
This works as an approximation because there are 1.609 kilometers in a mile, which is very close to the golden ratio (1.618) – the ratio between two Fibonacci numbers.
Discussion
No comments yet.