You can write a fibonacci function that works in linear time and with a constant memory area, you do not need a list to save them. Here's a recursive version (however, if n is large enough, it will be https://stackoverflow.com/a/168269/ )
def fib(a, b, n): if n == 1: return a else: return fib(a+b, a, n-1) print fib(1, 0, 10)
This function calls itself only once (as a result, around N calls for parameter N), unlike your solution, which calls itself twice (about 2 ^ N calls for parameter N).
Here is a version that will never use stackoverflow and uses a loop instead of recursion:
def fib(n): a = 1 b = 0 while n > 1: a, b = a+b, a n = n - 1 return a print fib(100000)
And this is fast enough:
$ time python fibo.py 3364476487643178326662161200510754331030214846068006390656476... real 0m0.869s
But calling fib until you get a big enough result is not perfect: the first numbers in a series are computed several times. You can calculate the following fibonacci number and check its size in one cycle:
a = 1 b = 0 n = 1 while len(str(a)) != 1000: a, b = a+b, a n = n + 1 print "%d has 1000 digits, n = %d" % (a, n)
toasted_flakes
source share