Professional Documents
Culture Documents
Complexity: O(3+36+3)=O(42)
i=0,flag=0; ---------------O(1)
while(i<n){ ----------------O(n)-----------------|
if(a[i]==x) --------------O(1)----| |
{ flag=i; --------------- O(1) | |-- O(n*(3))=O(3n)
terminate from loop}--O(1) |--O(3) |
else increment I---------O(1)----|-------------|
}
if(flag==0) ------O(1)---------|
return 0-----O(1) |
else |---O(2)
return i------O(1)---------|
3. Factorial: Recursive
n-> a positive number whose factorial is to be found
fact(n){
if n<=1----------------------O(1) -----|
return 0 -----------O(1) |
else |--O(1+n)
return n*fact(n-1)---O(n) --|
Complexity: O(n+1)
4.Factorial: Iterative
Complexity: O(3n+1)
n and k -> 2 no.s using which we have to find binomial coefficient as in nCk and n>k.
arr[n+1][k+1]->array required to store solution
while(i<=n){ ----------------------O(n)-----------------------------------|
for(j=0;j<( (i<k) ? i:k);j++)---------------O(k)----------| |
{if j=0 or j=i --------------------------O(1)---| |-O(k*3) = O(3k) |-O(n*3k)
c[i][j]=0-------------------------------O(1) |-O(3)| | =O(3nk)
else c[i][j]=c[i-1][j-1]+c[i-1][j]}}-------O(2)---|------|------------------------|
Complexity: O(3nk)
7.Give a recursive algorithm to compute the binomial coefficient
n and k -> 2 no.s using which we have to find binomial coefficient as in nCk.
bin(n,k){
if n==k or k==0------------------O(1)-----------|
return 1 ----------------O(1) |
else |-O(2n-1 + 1)
n-1
bin(n-1,k-1) + bin(n-1,k)-----O(2 )------|
Complexity : O(2n-1 + 1)
8. Ackermann’s function:
Complexity: O(5n+2)
9.Given a positive integer determine whether it is the sum of all of
its divisors
i=2,sum=0 ----------O(1)
while(i<=n){ -------O(n)--------|
if(n%i==0) -----------O(1) |
sum += i -----------O(2) |---O(n*(1+2+1))=O(4n)
increment i }----------O(1) -------|
if(sum==n)--------|
true |-------O(1)
else |
false---------|
Complexity: O(1+4n+1) = O(4n+2)
10.GCD of 2 numbers
gcd(a,b){
if a mod b = 0 then return b -------O(2)
gcd(b,a mod b)--------------------------O(log a)
Complexity: O(log(a)+2)