201. Factorial by Recursion
Foundation1000 ms256 MBSolved by 0%
Print n!, which is every whole number from 1 to n multiplied together:
5! = 5 x 4 x 3 x 2 x 1 = 120
By definition 0! is 1, and that is not a special case to handle separately.
It is the base case your recursion stops at.
The whole function is two lines of thought: if n is 0 or 1 the answer is 1,
otherwise it is n times the factorial of n - 1.
Constraints - `0 ≤ n ≤ 20`
Input
A single line containing one integer n.
Output
Print one integer, the value of n!.
Input5
Output120
Noteis the worked example from the statement
Input0
Output1
Noteis the base case, where the answer is 1 rather than 0
Hints
Four rungs, in order. The last two open once you have submitted an attempt. A wrong one counts.
Hint 1Where to start
Hint 2The approachOpen hint 1 first. This one carries on from it.
Hint 3PseudocodeOpen hint 2 first. This one carries on from it.
Hint 4Full solutionOpen hint 3 first. This one carries on from it.