having fun with code

Fibonacci

Fibonacci is a fast growing sequence that can easily overflow your integer variables. Fortunately, Python doesn’t have this problem, since it can handle huge integer numbers.

  1. #!/usr/bin/env python
  2. def fib(n):
  3.   if n==0 or n==1:
  4.     ret = n
  5.   else:
  6.     ret = fib(n-1) + fib(n-2)
  7.   return ret
  8.  
  9. for i in range(1000):
  10.   print fib(i)

The example avobe has a big performance issue, due to the recursive calls to calculate n-1 and n-2 values, which are calculated multiple times over and over. By storing the results on a list we solve this issue, although we now relay on the amount of available memory.

  1. #!/usr/bin/env python
  2. fibs = []
  3. def fib(n):
  4.   if n==0 or n==1:
  5.     ret = n
  6.   elif n < len(fibs):
  7.     ret = fibs[n]
  8.   else:
  9.     ret = fib(n-1) + fib(n-2)
  10.     fibs.append(ret)
  11.   return ret
  12.  
  13. for i in range(1000):
  14.   print fib(i)

Thus, Fib(1000) = 43,466,557,686,937,456,435,688,527,675,040,625,802,
564,660,517,371,780,402,481,729,089,536,555,417,949,051,890,403,879,840,079,
255,169,295,922,593,080,322,634,775,209,689,623,239,873,322,471,161,642,996,
440,906,533,187,938,298,969,649,928,516,003,704,476,137,795,166,849,228,875

Related Posts:

Leave a Reply

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Additional comments powered by BackType

About the blog

This is a blog about development, focused mainly on Javascript but also other languages like python, shell scripts and more.

About the author

Eneko Alonso is a software engineer and UI developer with more than eight years of experience in software and web development. He lives in San Luis Obispo, California and works at LEVEL Studios.

Contact Info

Contact Info