Module 1 Algo Cncpts
Module 1 Algo Cncpts
Programming Exercises:
1. In each of the below mentioned scenario, deduce the general formula f(n) where n is the
input size for a given instance of the problem:
a. for(i=0;i<100;i+=2)
statement block;
Ans:
The loop runs from 0 to 100 with a step of 2.
Total iterations = 100/2=50
f(n) = 50 (constant)
b. for(i=1000;i>0;i/=2)
statement block;
Ans:
The loop divides i by 2 until it reaches 0.
Iterations = log2(1000)
f(n) = O(\log n)
c. for(i=0;i<10;i++)
for(j=1; j<10;j*=2)
statement block;
Ans:
Outer loop: 10 iterations.
Inner loop: Iterates for log2(10)
Total iterations = 10⋅log2(10)
f(n) = O(n \log n)
d. for(i=0;i<10;i++)
for(j=0; j<10;j++)
statement block;
Ans:
Outer loop: 10 iterations.
Inner loop: 10 iterations per outer iteration.
Total iterations = 10*10=100
f(n) = O(n^2)
e. for(i=0;i<10;i++)
statement block;
Ans:
Outer loop: 10 iterations.
Inner loop: i+1 iterations for each i.
Total iterations = ∑i=010(i+1)=1+2+3+...+10
=10⋅(10+1) / 2
=55
f(n) = O(n^2)
2. What is a polynomial function and an exponential function? Provide examples in each of
the functions.
Ans:
Polynomial Function:
A function of the form f(n)=an^k+bn^(k−1)+...+c, where k is a
non-negative integer.
Example: f(n)=3n^2+2n+1
Exponential Function:
A function of the form f(n)=a⋅b^n, where b>1.
Example: f(n)=2^n
3. Let f(n)=2^n and g(n)=n^2. Compare the values of f(n) and g(n) for n=1 to n, and provide
the conclusion on the rate of increase among them.
Ans:
Calculations for f(n) and g(n) :
n f(n) = 2^n g(n) = n^2
1 2 1
2 4 4
3 8 9
4 16 16
5 32 25
6 64 36
7 128 49
8 256 64
9 512 81
10 1024 100
Observations:
1. At smaller values of n (e.g., n=1 and n=2), f(n) and g(n) are close, and g(n) might
even surpass f(n) temporarily.
2. From n=5 onwards, f(n) = 2^n grows much faster than g(n) = n^2, and this trend
continues as n increases.
Conclusion:
● The growth rate of f(n)=2^n = 2^n is exponential, while the growth rate of g(n) =
n^2 is polynomial.
● Exponential growth outpaces polynomial growth as n increases. Hence, f(n) will
eventually become much larger than g(n), regardless of how large g(n) is initially.