Factorial of a given number

Pattern: Maths basics

easy

Multiply 1 × 2 × ... × n with one running product, and pick a type big enough to hold it.

The problem

You are given a whole number n from 0 to 20. Return n factorial, written n!, which is the product 1 × 2 × 3 × ... × n. By definition 0! is 1. For example, 5! = 120.

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.

Think first

  • Work out 1!, 2!, 3!, 4! and 5! by hand. How does each one come from the one before it?
  • What should the product start at, so that multiplying into it doesn't change the answer?
  • 12! is 479,001,600. 13! is 13 times that. Will it fit in a 32-bit int, whose largest value is 2,147,483,647?

Hints

    Brute force, and why it fails

    The textbook definition is recursive: n! = n × (n - 1)!, with 0! = 1. A recursive function that follows it is correct and also does n multiplications. It does, however, keep n calls waiting on the call stack at once.

    A loop does the same multiplications with no stack at all. For n up to 20 either way is instant; the loop is simply the cleaner habit.

    The key insight

    A running product, started at 1, turns n! into one loop. The real trap is size, not speed: factorials grow so fast that the type you store them in matters from n = 13 on.

    Dry run

    10 
    21 
    32 
    43 
    54 
    n5
    result1

    n = 5 and result starts at 1. The loop starts at i = 2, because multiplying by 1 changes nothing.

    Step 1 of 6

    The plan

    result = 1
    for i from 2 to n:
        result = result * i     # result now holds i!
    return result
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One multiplication per number from 2 to n, and a single variable for the product.

    Edge cases

    • n = 0 and n = 1 both return 1, because the loop does not run.
    • 12! = 479,001,600 is the last factorial that fits in a 32-bit int.
    • 13! = 6,227,020,800 needs 64 bits.
    • 20! = 2,432,902,008,176,640,000 is the last one that fits in 64 bits. For anything larger see "Find factorial of a large number".
    I've built my logic, show the code

    Java

    class Solution {
        public long factorial(int n) {
            long result = 1;
            for (int i = 2; i <= n; i++) {
                result = result * i;
            }
            return result;
        }
    }

    C++

    class Solution {
    public:
        long long factorial(int n) {
            long long result = 1;
            for (int i = 2; i <= n; i++) {
                result = result * i;
            }
            return result;
        }
    };

    Python

    class Solution:
        def factorial(self, n):
            result = 1
            for i in range(2, n + 1):
                result = result * i
            return result

    Common mistakes

    • Starting the product at 0, which makes every answer 0.
    • Storing the result in a 32-bit int, which silently gives a wrong answer from 13! on.
    • Looping only up to n - 1, which returns (n - 1)!.

    Similar problems