0
Problems with the challenge
Can anyone explain why in this exercise the result is 4? Why fact(1) is 1, but not 0? int fact(int n) { if (!n) return 1; return n * fact(n-1); } int main () { cout << fact(3) - fact(2); }
3 Answers
+ 1
tippfehler, in your code "fact(-1)" returns -1.
In C/C++ a negation of a non-zero number returns 0 (false) and a negation of 0 returns 1 (true). The compiler does an implicit cast of 0/1 integers to their boolean equivalents false/true and vice-versa.
+ 2
In the if statement, when n is false, !n is true. When !n is true, the function returns 1 (what's inside the if statement), else it does n * fact(n-1).
fact(1) = 1
fact(0) = 1
fact(2) = 2 * 1
fact(3) = 3* fact(2) * fact(1) = 6
fact(3) - fact(2) = 6 - 2 = 4.
0
Okay, but why 1 and 0 in fact(1) and fact(0) is "!n"? And what if I write fact(-1)?