Program and time complexity of factorial using iteration and recursion in C
#include <stdio.h>
void main() {
int n;
int i;
int f=1;
printf("enter number");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("factorial of a number is %d",f);
}
Factorial using recursion
#include <stdio.h>
int fact(int n)
{
int f;
if(n==1)
return(1);
else
f=n*fact(n-1);
return(f);
}
void main() {
int n;
int i;
printf("enter number");
scanf("%d",&n);
printf("factorial of a number is %d",fact(n));
}
Time complexity using recursion in factorial
T(n)=T(n-1)+c
T(n-1)=T(n-1-1)+c
Put the value of T(n-1)
T(n)=T(n-2)+2c
In general term
T(n)=T(n-k)+kc
n-k=0
n=k
T(n)=T(0)+kc
T(n)=1+nc
T(n)=O(n)
So time complexity of factorial using recursion is O(n) and space complexity is also O(n).
0 Comments