Try to write down the recurrence relation for running time of recursive algorithm for finding factorial(n). Suggest the base cases for that recurrence relation.
I could not solve this problem, Can someone explain it?
Try to write down the recurrence relation for running time of recursive algorithm for finding factorial(n). Suggest the base cases for that recurrence relation.
I could not solve this problem, Can someone explain it?
Factorial can be determine by this algorithm
1: Read number n.
2. Initialize i and fact to 1.
3. Repeat step 4 and step 5 while i is not equal to n.
4. fact <- fact * i
5. i <- i +1
6. Return fact
In short if we write down this by recurrence relation then it will be -
int Fact(int num) {
if(num <= 1) {
return 1;
}
else {
return num * Fact(num - 1);
}
}
Basically factorial of a number num
will be factorial of Fact[num - 1] * num
.
So we can write it like this -
int fact[num+1];
fact[0] = 1;
for(int i = 1; i <= num; i++) {
fact[i] = fact[i-1] * i; // recurrence relation is here
}
printf("%d\n", fact[num]);