Advertisement
paulogp

Série de Fibonacci

Jul 13th, 2011
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. # Determinação dos primeiros k termos da série de Fibonacci, usando uma função recursiva:
  2. # f(0) = f(1) = 1; f(n) = f(n - 1) + f(n - 2) para n = 2, 3, ...
  3.  
  4. def def_fib_rec(the_n):
  5.     """ slow algorithm """
  6.     assert the_n >= 0
  7.  
  8.     if the_n < 2:
  9.         return the_n
  10.  
  11.     return def_fib_rec(the_n-2) + def_fib_rec(the_n-1)
  12.  
  13.  
  14.  
  15. def def_bits(the_n):
  16.     """ represent an integer as an array of binary digits  """
  17.     the_bits = []
  18.  
  19.     while the_n > 0:
  20.         the_n, the_bit = divmod(the_n, 2)
  21.         the_bits.append(the_bit)
  22.  
  23.     the_bits.reverse()
  24.  
  25.     return the_bits
  26.  
  27.  
  28. def def_fib_fast(the_n):
  29.     """ good algorithm """
  30.     assert the_n >= 0
  31.  
  32.     the_a, the_b, the_c = 1, 0, 1
  33.  
  34.     for the_bit in def_bits(the_n):
  35.         if the_bit:
  36.             the_a, the_b = (the_a+the_c)*the_b, the_b*the_b + the_c*the_c
  37.         else:
  38.             the_a, the_b = the_a*the_a + the_b*the_b, (the_a+the_c)*the_b
  39.  
  40.         the_c = the_a + the_b
  41.  
  42.     return the_b
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement