Factorial of a Given Number

Pattern: Recursion basics

easy

Compute n! recursively from its own definition, n! = n × (n - 1)!, with 0! = 1! = 1 as the base case.

The problem

You are given a whole number n from 0 to 20. Return n! using recursion. n! is 1 × 2 × ... × n, and 0! is 1. For example, 4! = 24.

On the original site the problem is written a little differently, so use the link above for its exact wording. The function name factorial and the limit of 20 are this guide's own: 20! is the largest factorial that fits in a signed 64-bit integer. The loop version of this problem is "Factorial of a given number" in Maths basics.

Think first

  • How is 5! related to 4!?
  • Which small values of n have an answer you know without any multiplication?
  • What type must the answer have, given that 13! is over 6 billion?

Hints

    Brute force, and why it fails

    The loop version multiplies 2, 3, ..., n into a running product. It does the same n multiplications and uses constant memory, so outside this exercise it is the better choice. The recursive version is worth writing once because it is the definition turned straight into code, and it shows the call stack doing the bookkeeping that the loop does with a variable.

    The key insight

    The definition n! = n × (n - 1)! with 0! = 1 is a recursive function already. Each call multiplies its own n into the answer that comes back from below.

    Dry run

    f(4)0 
    waiting4 × ?

    Call factorial(4). 4 is more than 1, so it needs 4 × factorial(3) and waits. The array is the call stack.

    Step 1 of 7

    The plan

    function factorial(n):
        if n <= 1:
            return 1                      # 0! = 1! = 1
        return n * factorial(n - 1)
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    There are about n calls with one multiplication each, and up to n of them are open on the stack at once.

    Edge cases

    • n = 0 and n = 1 return 1 from the base case.
    • 12! = 479,001,600 is the last value that fits in 32 bits; 13! needs 64 bits.
    • 20! = 2,432,902,008,176,640,000 is the largest value that fits in 64 bits.
    I've built my logic, show the code

    Java

    class Solution {
        public long factorial(int n) {
            if (n <= 1) {
                return 1;                   // base case: 0! = 1! = 1
            }
            return n * factorial(n - 1);    // n! = n * (n - 1)!
        }
    }

    C++

    class Solution {
    public:
        long long factorial(int n) {
            if (n <= 1) {
                return 1;                   // base case: 0! = 1! = 1
            }
            return n * factorial(n - 1);    // n! = n * (n - 1)!
        }
    };

    Python

    class Solution:
        def factorial(self, n):
            if n <= 1:
                return 1                        # base case: 0! = 1! = 1
            return n * self.factorial(n - 1)    # n! = n * (n - 1)!

    Common mistakes

    • A base case of n == 1 only, which recurses forever for n = 0.
    • Returning a 32-bit int, which is wrong from 13! on.
    • Returning factorial(n - 1) without multiplying by n.

    Similar problems