Find factorial of a large number

Pattern: Maths basics

easy

Compute factorials far beyond 64 bits by storing the answer as a list of digits and multiplying with carries, the way you do on paper.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

You are given a whole number n from 0 to 1000. Return n! (1 × 2 × ... × n, with 0! = 1) written out in full as a string of digits. For example, 25! is 15511210043330985984000000, and 1000! has 2,568 digits.

This problem comes from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name largeFactorial and the limit of 1000 are this guide's own.

Think first

  • 20! is the largest factorial that fits in a 64-bit integer. How will you hold a number with thousands of digits?
  • Multiply 128 by 7 on paper. Which digit do you start with, and what do you do with the carry?
  • When a carry is left over after the leading digit, where does it go?

Hints

    Brute force, and why it fails

    Use a 64-bit integer and multiply as usual. It works up to 20! and then silently gives wrong answers. Java's BigInteger and Python's built-in integers can hold huge numbers, and in Python result = result * i really is a fine answer. The point of this problem in interviews is to do it without such a type, which is what this guide builds. The same digit-list idea is how big-number types work inside.

    The key insight

    A number is just a list of digits. Multiplying it by a small number is one pass over the list with a carry, exactly as on paper. Storing the digits last-first makes a growing carry easy to append.

    Dry run

    10 
    n5
    reads as1

    n = 5. Store the answer as a list of digits, last digit first, so a carry can always be added at the end of the list. Start with [1].

    Step 1 of 6

    The plan

    digits = [1]                       # last digit first
    for i from 2 to n:
        carry = 0
        for k from 0 to length(digits) - 1:
            value = digits[k] * i + carry
            digits[k] = value mod 10
            carry = value div 10
        while carry > 0:               # the carry can need several new digits
            append carry mod 10 to digits
            carry = carry div 10
    return digits read from the last index down to 0, as text
    

    Complexity

    Time
    O(n × D)
    Space
    O(D)

    D is the number of digits in n!, which grows a little faster than n (2,568 for n = 1000). Each of the n multiplications passes over all the digits once. For n = 1000 that is about 2.5 million small steps.

    Edge cases

    • n = 0 and n = 1 return "1".
    • 21! is the first one that no longer fits in 64 bits.
    • 25! ends in six zeros. Zeros inside the list are ordinary digits and need no special care.
    • Every product digit × i + carry is below 10,000 for i up to 1000, so a 32-bit integer is plenty for it.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public String largeFactorial(int n) {
            List<Integer> digits = new ArrayList<>();
            digits.add(1);   // least significant digit first
            for (int i = 2; i <= n; i++) {
                int carry = 0;
                for (int k = 0; k < digits.size(); k++) {
                    int value = digits.get(k) * i + carry;
                    digits.set(k, value % 10);
                    carry = value / 10;
                }
                while (carry > 0) {
                    digits.add(carry % 10);
                    carry = carry / 10;
                }
            }
            StringBuilder text = new StringBuilder();
            for (int k = digits.size() - 1; k >= 0; k--) {
                text.append(digits.get(k).intValue());
            }
            return text.toString();
        }
    }

    C++

    class Solution {
    public:
        string largeFactorial(int n) {
            vector<int> digits(1, 1);   // least significant digit first
            for (int i = 2; i <= n; i++) {
                int carry = 0;
                for (size_t k = 0; k < digits.size(); k++) {
                    int value = digits[k] * i + carry;
                    digits[k] = value % 10;
                    carry = value / 10;
                }
                while (carry > 0) {
                    digits.push_back(carry % 10);
                    carry = carry / 10;
                }
            }
            string text;
            for (int k = static_cast<int>(digits.size()) - 1; k >= 0; k--) {
                text.push_back(static_cast<char>('0' + digits[k]));
            }
            return text;
        }
    };

    Python

    class Solution:
        def largeFactorial(self, n):
            digits = [1]   # least significant digit first
            for i in range(2, n + 1):
                carry = 0
                for k in range(len(digits)):
                    value = digits[k] * i + carry
                    digits[k] = value % 10
                    carry = value // 10
                while carry > 0:
                    digits.append(carry % 10)
                    carry = carry // 10
            return "".join(str(d) for d in reversed(digits))

    Common mistakes

    • Storing the digits first-digit-first, which makes every carry run the wrong way and new digits expensive to add.
    • Adding only one digit for a leftover carry, when it may need several.
    • Printing the list in storage order, which writes the number backwards.

    Similar problems