Back to problems
COMP2521
Recursion: Factorial
Recursion: factorial n!
Compute n! (the factorial of n) recursively. n! = n × (n-1) × … × 2 × 1, with 0! = 1.
This is the same fact shown in the page's animation. Complete it, remembering recursion's two parts:
- Base case: when
n == 0, return1directly (we have bottomed out; stop recursing). - Recursive case: return
n * fact(n - 1)(shrink the problem by 1 and hand it to a smaller copy of itself).
Pitfalls (straight from the bug lab): (1) omitting the baseif (n == 0) return 1;causes infinite recursion and a stack overflow. (2) Returning0instead of1in the base makes the whole product collapse to0(the identity for multiplication is 1, not 0). (3) The recursive call must befact(n - 1); dropping the-1means n never shrinks and the base is never reached.
Input
- One line: integer
n(0 ≤ n ≤ 12, the result fits inint).
Output
- One line: the value of
n!.
Example: input 4 -> 24 (since 4×3×2×1 = 24).
Samples
stdin
4
expected
24
stdin
0
expected
1
c-dcc
14