The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be F1 = 1, F2 = 1, F3 = 2, F4 = 3, F5 = 5, F6 = 8, F7 = 13, F8 = 21, F9 = 34, F10 = 55, F11 = 89, F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the first term in the Fibonacci sequence to contain 1000 digits?
I made a brute force solution in Python, but it takes absolutely forever to calculate the actual solution. Can anyone suggest a non brute force solution?
def Fibonacci(NthTerm):
if NthTerm == 1 or NthTerm == 2:
return 1 # Challenge defines 1st and 2nd term as == 1
else: # recursive definition of Fib term
return Fibonacci(NthTerm-1) + Fibonacci(NthTerm-2)
FirstTerm = 0 # For scope to include Term in scope of print on line 13
for Term in range(1, 1000): # Arbitrary range
FibValue = str(Fibonacci(Term)) # Convert integer to string for len()
if len(FibValue) == 1000:
FirstTerm = Term
break # Stop there
else:
continue # Go to next number
print "The first term in the\nFibonacci sequence to\ncontain 1000 digits\nis the", FirstTerm, "term."
You can write a fibonacci function that runs in linear time and with constant memory footprint, you don't need a list to keep them. Here's a recursive version (however, if n is big enough, it will just stackoverflow)
This function calls itself only once (resulting in around N calls for a parameter N), in contrast with your solution which calls itself twice (around 2^N calls for a parameter N).
Here's a version that won't ever stackoverflow and uses a loop instead of recursion:
And that's fast enough:
But calling
fib
until you get a result big enough isn't perfect: the first numbers of the serie are calculated multiple times. You can calculate the next fibonacci number and check its size in the same loop:Instead of recursively calculating every term each time, make an array of terms, then you can calculate a term by adding terms[-1] and terms[-2]
Here is the Java version in constant space and linear time:
Use binet's formula. It's the fastest way to find Fibonacci numbers, and it doesn't use recursion.
you can use Memorization :
You can try to use newton's approximation method on binet's formula. The idea is to find a tangent line on the graph and use the x-intercept of that line to approximate the value of the zero of the graph.