Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Basics

Factorial of a Large Number

Medium · Basics · Asked at Amazon, Microsoft, Samsung, TCS, Infosys

Print the exact value of n! (n factorial), which can have more than a thousand digits.

Input

A single integer n.

Output

The digits of n!.

Constraints

Store the number as an array of digits (least significant first) and multiply it by 2, 3, …, n with carries, like multiplication on paper. 500! has 1135 digits.

Example 1

Input

5

Output

120

Example 2

Input

0

Output

1

Hints

  1. 20! already overflows a 64-bit integer.
  2. Store the number as a list of digits, least significant first.
  3. Multiply digit by digit with a carry, as you would on paper.

Approach

Start with the digit list [1]. For each i from 2 to n, multiply every digit by i, add the carry, keep (product % 10) and carry (product / 10) to the next digit; after the last digit, append the remaining carry digit by digit. Print the digits in reverse. Python integers are arbitrary precision, but the digit-array method is what interviews expect.

Complexity: O(n · D) time, D ≈ 1135 digits · O(D) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> d = {1}; // least significant digit first
    for (int i = 2; i <= n; i++) {
        int carry = 0;
        for (auto &x : d) {
            int p = x * i + carry;
            x = p % 10;
            carry = p / 10;
        }
        while (carry) {
            d.push_back(carry % 10);
            carry /= 10;
        }
    }
    for (int k = d.size() - 1; k >= 0; k--) cout << d[k];
    cout << "\n";
    return 0;
}

Python solution

n = int(input())
d = [1]  # least significant digit first
for i in range(2, n + 1):
    carry = 0
    for k in range(len(d)):
        p = d[k] * i + carry
        d[k] = p % 10
        carry = p // 10
    while carry:
        d.append(carry % 10)
        carry //= 10
print("".join(map(str, reversed(d))))

Java solution

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int n = new Scanner(System.in).nextInt();
        ArrayList<Integer> d = new ArrayList<>();
        d.add(1);
        for (int i = 2; i <= n; i++) {
            int carry = 0;
            for (int k = 0; k < d.size(); k++) {
                int p = d.get(k) * i + carry;
                d.set(k, p % 10);
                carry = p / 10;
            }
            while (carry > 0) {
                d.add(carry % 10);
                carry /= 10;
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int k = d.size() - 1; k >= 0; k--) sb.append(d.get(k));
        System.out.println(sb);
    }
}

Solve Factorial of a Large Number online · All practice problems