easyRecursion 0 views

Factorial with Recursion

Practice writing a recursive function with a clear base case and recursive case.

Given a non-negative integer n, return n! (n factorial), defined as the product of all positive integers up to n, with 0! = 1.

Implement this recursively. This is a basics exercise for recursion itself — the goal is to internalize the shape every recursive function shares, not to find the fastest way to multiply numbers.

Example 1

Input: n = 5

Output: 120

Explanation: 5! = 5 * 4 * 3 * 2 * 1 = 120.

Example 2

Input: n = 0

Output: 1

Explanation: By definition, 0! = 1.

Example 3

Input: n = 1

Output: 1

Constraints

  • 0 <= n <= 12

Follow-up

Can you rewrite this iteratively, without recursion? Which version would you actually ship?

Hints

Companies

No companies reported yet.

Discussion

Sign in to join the discussion.

Loading discussion...

Test results

No test cases yet.