Reputation: 67
I'm learning C and came up with this one-line factorial function using a ternary operator on the return, but it always returns 1.
#include <stdio.h>
int factorial(int n){
return (n > 1) ? factorial(n -1) : 1;
}
int main() {
for(int i = 0; i < 10; i++){
printf("%d factorial is %d\n",i,factorial(i));
}
return 0;
}
You can see the code returns 1 for values 0 through 9 in this link: https://code.sololearn.com/c7uSnfxw92sl/#c
Upvotes: 1
Views: 225
Reputation: 906
You forgot to multiply by n
int factorial(int n){
return (n > 1) ? n * factorial(n -1) : 1;
}
Upvotes: 4
Reputation: 48745
That is very easy since we can use the substitution rules. Eg.
factorial(10); // ==
(10 > 1) ? factorial(10 - 1) : 1 // ==
(9 > 1) ? factorial(9 - 1) : 1 // ==
(8 > 1) ? factorial(8 - 1) : 1 // ==
(7 > 1) ? factorial(7 - 1) : 1 // ==
(6 > 1) ? factorial(6 - 1) : 1 // ==
(5 > 1) ? factorial(5 - 1) : 1 // ==
(4 > 1) ? factorial(4 - 1) : 1 // ==
(3 > 1) ? factorial(3 - 1) : 1 // ==
(2 > 1) ? factorial(2 - 1) : 1 // ==
(1 > 1) ? factorial(1 - 1) : 1 // ==
1
Your function is broken. It does not multiply n with the result of factorial(n - 1). You could also do it with an accumulator for it to become tail recursion, but you cannot just replace it with factorial(n - 1)
since it will not compute the same as factorial(n)
.
Upvotes: 1