Write program to calculate factorial of a number
0! = 1
1! = 1
//Time complexity O(n) and Space complexity O(n)
int factorial_recursive(int n) {
if(n < 0) {
return 0;
}
if(n == 0) {
return 1;
}
return factorial_recursive(n - 1) * n;
}
//Time complexity O(n) and Space complexity O(1)
int factorial_iterative(int n) {
if(n < 0) {
return 0;
}
if(n == 0) {
return 1;
}
int result = 1;
for(int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
Comments
Post a Comment