1.
Write a program non-recursive and recursive program to calculate
Fibonacci numbers and analyze their time and space complexity.
Non-recursive Algorithm
Analysis:
Two cases (1) n = 0 or 1 and (2) n > 1.
1) When n = 0 or 1, lines 4 and 5 get executed once each. Since
each line has an s/e of 1, the total step count for this case is 2.
2) When n > 1, lines 4, 8, and 14 are each executed once. Line 9
gets executed n times, and lines 11 and 12 get executed n-1
times each. Line 8 has an s/e of 2, line 12 has an s/e of 2, and
line 13 has an s/e of 0. The remaining lines that get executed
3) have s/e’s of 1. The total steps for the case n > 1 is therefore 4n
+ 1.
Recursive Algorithm
Algorithm rFibonacci(n)
if (n <= 1)
return n;
else
return rFibonacci(n - 1) + rFibonacci(n - 2); }
Analysis
T(n) = T(n-1) + T(n-2) + c
= 2T(n-1) + c //from the approximation T(n-1) ~ T(n-2)
= 2*(2T(n-2) + c) + c
= 4T(n-2) + 3c
= 8T(n-3) + 7c
= 2k * T(n - k) + (2k - 1)*c
Let's find the value of k for which: n - k = 0
k=n
T(n) = 2n * T(0) + (2n - 1)*c
= 2n * (1 + c) - c
T(n) = 2n
Non-Recursive Program
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("Enter number of terms "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto", nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Output:
Enter number of terms 4 Fibonacci sequence:
2
Recursive Program
def fibonacci(n):
if(n <= 1):
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input("Enter number of terms:"))
print("Fibonacci sequence:")
for i in range(n):
print(fibonacci(i))
Output:
Enter number of terms:4 Fibonacci sequence: