Bscs-402 Data Structure Lab 1
Bscs-402 Data Structure Lab 1
LAB 1
Q1 . Your task is to design two different algorithms in
python/C++ which calculates factorial of a number entered
by user
(you may choose iterative and recursive approach)
def factorial1(N):
# N = input("Input Number : ")
i = int(N)
factorial = int(N)
while (i > 1):
i = i-1
factorial = factorial * i
return factorial
Page 1
Algorithm 2 For Loop (iterative)
def factorial2(N):
# N = input("Input Number : ")
i = int(N)
factorial = int(N)
for j in range(1,int(N)):
factorial = factorial * j
return factorial
Algorithm 3 (Recursive)
def factorial3(N):
"""This is a recursive function
to find the factorial of an integer"""
if N == 1:
return 1
else:
a = (N * factorial3(N - 1))
return a
Page 2
Q2.Compare the performance of the above two algorithms
by finding the time required to execute the algorithms (You
can use %timeit )
def Efficiency(Factorial,Times):
Page 3
Results of Algorithm
Page 4
Graphs Comparison
def mainPlot():
x= []
while1 = []
for1 = []
recur = []
for i in range (1,850):
x.append(i)
while1.append(timeit.timeit(lambda :factorial1(i),
number = 500))
for1.append(timeit.timeit(lambda: factorial2(i),
number=500))
recur.append(timeit.timeit(lambda: factorial3(i),
number=500))
graph.plot(x,while1)
graph.plot(x,for1)
graph.plot(x,recur)
graph.show()
Value for factorial from 1 till 800
Each Value for factorial will run for 50 times
Page 5
Q3.Now compares the algorithmic efficiency using big-O
notation
factorial = int(N) 1 1 1
i = i-1 2 n 2n
factorial = factorial * i 2 n 2n
Page 6
factorial = int(N) 1 1 1
factorial = factorial * j 2 n 2n
return 1 1 1 1
else: 1 n n
a = (N * factorial3(N - 1)) 3 n 3n
Conclusion:
▪ All Algorithms have same complexity of O(n).
Page 7
Page 8