Homework – Chapter 1
• Given the Fibonacci number as
1 2 3 5 8 13 21 34…
where the next Fibonacci number will be
the sum of its previous two Fibonacci
• The number of 8 is the sum of 3 and 5.
• The next number will be 55 since it is the sum of
21 and 34.
1. Write a recursive algorithm to generate
the Fibonacci number N.
int Fibonacci (int N)
if (N <= 2)
return Fibonacci(N-1) + Fibonacci(N-2);
2. Write a non-recursive algorithm using
loop structure to generate the Fibonacci
int Fibonacci2 (int N)
if (N <= 2)
Let N1 = 1, N2 = 2, Total = 0;
for (i = 3 to N)
Total = N1 + N2;
N1 = N2;
N2 = Total;
3. Discuss the execution efficiency of these
– The process of the recursive Fibonacci() can be illustrated by
the following tree structure.
3 4 5
1 2 2 3 3 4
1 2 1 2 2 3
– Space complexity of Fibonacci(): 1 2
• At most N-1 stack frames (the depth of the tree) are
pushed into function call stack when Fibonacci() is called.
Therefore, the complexity is O(N).
– Time complexity of Fibonacci():
• Therefore, the time complexity depends on how many
nodes the tree has, which is O(2N).
– Space complexity of Fibonacci2():
• Only a fix number of automatic variables are
required. Therefore, the complexity is O(1).
– Time complexity of Fibonacci2():
• The for-loop runs in N-2 times. Its body perform
addition in O(1) for each iteration. Therefore, the
total computing time is O(N).
– Fibonacci2() is more efficient than
Fibonacci(). Its space complexity and time
complexity are relatively lower.
• Ordering by asymptotic growth rates:
– Please write computation!
log(n!) < log(nn) = O(n logn)
Let S = 4logn
logS = log4logn = log22logn = 2logn = logn2
∴S = n2 = O(n2)
(C) (n-1)! = O(n!)
(D) n．2n < 2n．2n = 22n = O(2n)
∴ (A) < (B) < (D) < (C)
Let S = (logn)logn
log S = (logn)(loglogn) = log(nloglogn)
S = nloglogn < nlogn < 2n
log n log n log n 1/ n
lim lim lim 0
n log 2 n n n log 2 n log 2
n nlogn 2n
1 1 2
10 10 1024
100 104 2100
… … …
2n is growing faster than nlogn.
∴ (A) < (B) < (E) < (D) < (C)