03 October 2024 14:20
1) Program to calculate factorial of a given number.
res = 1, n = 5
for(i=1; i<=n; i++) O(n)
res = res * i
Print(res)
We traverse through the loop n times. As n increases time
required Also increases.
As, Time is proportional to n. Hence, O(n) -> Orderof(n)
2) Print 2-D Matrix of size n*n.
for( i = 0; i<n; i++)
{
for(j=0; j<n; j++)
{
Print(arr[i][j])
}
}
Here, there is loop inside loop. For every iteration of
outer loop, the innermost loop goes through all the
iterations.
So, no. of iterations for inner loop are n*n
As, Time Hence, O(
3) Print the given number in binary format.
Algorithm : Divide the given number by 2 and collect
10/2 = 5 -> remainder 0
the remainder.
5/2 = 2 -> remainder 1
While(n > 0)
2/2 = 1 -> remainder 0
{
1/2 = 0 -> remainder 1
Print(n%2)
N = n/2
Going in reverse order the binary of 10 is 1010
}
For 10 there are only 4 iterations
For 1000 there are 10 iterations
Here, Each time we are dividing the number in parts. So
we are performing partitioning.
Whenever there is partitioning, the calculation is
Time_complexity Page 1
Take log on both sides
2^itr = n
Itr * Log 2 = log n
Itrs = log n / log 2
Time proportional to
Log n / log 2
1/log 2 is constant in theory of proportionality
Hence , time = log n
4) Print table of given number
For(I = 1;i<=10;i++)
{
Print(num * i)
}
Time_complexity Page 2