Example 1
function x(num) {
if (num == 0) {
return 1;
}
else {
return (num * x(num - 1));
}
}
x(8);
8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
Result is 40320 as expected
Example 2
function x(num) {
if (num == 0) {
return 0;
}
else {
return (num + x(num - 1));
}
}
x(8);
8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
Result is 36 as expected
Example 3
function x(num) {
if (num == 0) {
return 0;
}
else {
return (num - x(num - 1));
}
}
x(8);
8 - 7 - 6 - 5 - 4 - 3 - 2 - 1 - 0
Result is 4
Can someone explain why?
Shouldn't the answer be -20?
a - b - c - d
is not the same thing asa - (b - (c - d))
since two-
signs make a+
. – Benjamin Gruenbaum 22 hours agonum
for 1 to abort, otherwise the correct recursion term would be8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 * 1
. – Paebbels 18 hours agox(7) = 7 - x(6)
, sox(8) = 8 - x(7) = 8 - (7 - x(6))
; and you can keep going from there. Also, it's 'subtraction' (just one 's'). – L Spice 17 hours ago