Professional Documents
Culture Documents
Ihab McShea
Misr University for Science and Technology
1 Fibonacci Numbers
Fibonacci1 sequence is a sequence of integers, characterized by the fact that
every number is the combination of the two numbers that precede the specic
number in the sequence:
0,1,1,2,3,5,8,13,21,34,55, ...
The Fibonacci sequence can be treated as a recursive function, where as
we have mentioned each function of n is the combination of the previous two
functions, f(n) = f(n-1) + f(n-2), so a sample recursion chart when you run the
function (the naive way) to get the 7th Fibonacci number is as follows:
The gure is actually not a complete one, but the point of that chart is to say
that to get the seventh Fibonacci number we have to recursively call the function
~ 25 times, we will discuss later how to reduce that time. The follwing code (in
Python) is the implementation of the naive Fibonacci sequence algorithm:
def Fib(n ):
1 (1175-1250) was an Italian mathematician, often called the most talented mathematician
of the middle ages.
1
i f n==0:
return 0
e l i f n==1:
return 1
else :
return Fib(n 1) + Fib(n 2)
Let's try guessing the solution to the recurrence formula, let's say it's some-
thing raised to n, an exponential function:
f(n) = for some constant
n
conditions in a minute.
F(n) = c1( ) + c2( )
1+ 5 n
1 5 n
c1+ c2=0 2 2
c1 = - c 2
F(1) = 1 = c1( ) + c2( )
1+ 5 1
1 5 1
= c1 ( ) - c1 ( )
2 2
1+ 5 1 1 5 1
=c1( ) = c1 ( 5)
2 5
2
2
c1 = , c2 =
1 1
the next sections we'll explore ways to reduce its running time from exponential
2
3
3.1 Case Study for b(7):
4
See? A little lighter, actually, much lighter. Assuming n-bit registers for
each entry of memo/dictionary data structure:
T(n) = T(n-1) + c
Where c is the the time needed to add n-bit numbers to the memo.
T(n) ~ O(n )
2