Find Factorial of a Large Number

Last Updated : 1 Sep, 2026

Given a non-negative integer n, find n! and return a list of integers representing the digits of the factorial. 

frame_3363

Examples: 

Input: n = 5
Output: [1, 2, 0]
Explanation: 5! = 1 × 2 × 3 × 4 × 5 = 120. The digits of 120 are [1, 2, 0].

Input: n = 10
Output: [3, 6, 2, 8, 8, 0, 0]
Explanation: 10! = 1 × 2 × 3 × ... × 10 = 3628800. The digits of 3628800 are [3, 6, 2, 8, 8, 0, 0].

Try It Yourself
redirect icon

[Naive Approach] Using Standard Integer - O(n) Time and O(1) Auxiliary Space

The idea is to calculate the factorial by multiplying all integers from 2 to n.

Initialize fact as 1 and multiply it by every integer from 2 to n.

Consider: n = 5

  • i = 2 -> fact = 1 × 2 = 2
  • i = 3 -> fact = 2 × 3 = 6
  • i = 4 -> fact = 6 × 4 = 24
  • i = 5 -> fact = 24 × 5 = 120

Thus, 5! = 120.

This approach works for small values of n, but factorial values grow very quickly. For example, 100! contains 158 digits, which cannot be stored in standard integer data types such as int or long.

Therefore, this approach can cause integer overflow for large values of n.

For small values of n, refer to the simple program for factorial.

[Better Approach] Using BigInteger / BigInt - O(n × d) Time and O(d) Auxiliary Space

The idea is to use an arbitrary-precision integer to store the factorial. Unlike standard integer types, these data types can store numbers with a very large number of digits.

  • Initialize fact as 1.
  • Multiply fact by every number from 2 to n.
  • Convert the final factorial into a string.
  • Store each digit of the string in the result list.
Java
import java.math.BigInteger;
import java.util.ArrayList;

class GFG {
    public static ArrayList<Integer> factorial(int n) {
        BigInteger fact = BigInteger.ONE;

        // Calculate factorial
        for (int i = 2; i <= n; i++) {
            fact = fact.multiply(BigInteger.valueOf(i));
        }

        ArrayList<Integer> ans = new ArrayList<>();

        // Store each digit in the result
        for (char ch : fact.toString().toCharArray()) {
            ans.add(ch - '0');
        }

        return ans;
    }

    public static void main(String[] args) {
        int n = 10;

        ArrayList<Integer> ans = factorial(n);

        System.out.println(ans);
    }
}
Python
def factorial(n):
    fact = 1

    # Calculate factorial
    for i in range(2, n + 1):
        fact *= i

    # Store each digit in the result
    ans = [int(ch) for ch in str(fact)]

    return ans


if __name__ == "__main__":
    n = 10

    ans = factorial(n)

    print(ans)
C#
using System;
using System.Numerics;
using System.Collections.Generic;

class GFG
{
    static List<int> factorial(int n)
    {
        BigInteger fact = BigInteger.One;

        // Calculate factorial
        for (int i = 2; i <= n; i++)
        {
            fact *= i;
        }

        List<int> ans = new List<int>();

        // Store each digit in the result
        foreach (char ch in fact.ToString())
        {
            ans.Add(ch - '0');
        }

        return ans;
    }

    static void Main()
    {
        int n = 10;

        List<int> ans = factorial(n);

        Console.WriteLine("[" + string.Join(", ", ans) + "]");
    }
}
JavaScript
function factorial(n) {
    let fact = 1n;

    // Calculate factorial
    for (let i = 2; i <= n; i++) {
        fact *= BigInt(i);
    }

    let ans = [];

    // Store each digit in the result
    for (let ch of fact.toString()) {
        ans.push(Number(ch));
    }

    return ans;
}

// Driver code
    let n = 10;

    let ans = factorial(n);

    console.log(ans);

Output
[3, 6, 2, 8, 8, 0, 0]

Note: This approach can be used only in languages that provide arbitrary-precision integer support. In C++, the standard library does not provide a BigInteger type, so the factorial can be calculated using manual digit-by-digit multiplication.

[Expected Approach] Manual Multiplication (Digit by Digit) - O(n × d) Time and O(d) Auxiliary Space

The idea is to store the factorial digit by digit in an array and multiply it by every number from 2 to n using manual multiplication.

  • Since n! can be too large for standard integer types, each digit is stored separately.
  • The digits are stored in reverse order, so the least significant digit is at index 0.
  • This allows multiplication to be performed from right to left while handling the carry.

For example, the number 120 is stored as: res = [0, 2, 1]

The multiplication is performed in the same way as manual multiplication.

2056958667

We multiply each digit by 5 from right to left and maintain a carry whenever the product is greater than 9.

The same process is repeated for every number from 2 to n.

Steps:

  • Initialize res[0] = 1 and set resSize = 1.
  • Traverse from x = 2 to n.
  • For each x, multiply it with every digit of res[] and maintain a carry.
  • For each digit, calculate prod = res[i] * x + carry, store prod % 10 in res[i], and update carry = prod / 10.
  • After processing all digits, store the remaining digits of carry in res[].
  • Traverse res[] from resSize - 1 to 0 to get the factorial digits in the required order.
C++
#include <bits/stdc++.h>
using namespace std;

vector<int> factorial(int n) {
    
    // Store digits in reverse order
    vector<int> res = {1};

    // Multiply by every number from 2 to n
    for (int x = 2; x <= n; x++) {
        int carry = 0;

        // Multiply x with each digit
        for (int i = 0; i < res.size(); i++) {
            int prod = res[i] * x + carry;

            res[i] = prod % 10;
            carry = prod / 10;
        }

        // Store remaining carry
        while (carry) {
            res.push_back(carry % 10);
            carry /= 10;
        }
    }

    // Convert digits to required order
    reverse(res.begin(), res.end());

    return res;
}

int main() {
    int n = 5;

    vector<int> ans = factorial(n);

    cout << "[";
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i];

        if (i + 1 < ans.size())
            cout << ", ";
    }
    cout << "]";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Collections;

class GFG {

    static ArrayList<Integer> factorial(int n) {

        // Store digits in reverse order
        ArrayList<Integer> res = new ArrayList<>();
        res.add(1);

        // Multiply by every number from 2 to n
        for (int x = 2; x <= n; x++) {
            int carry = 0;

            // Multiply x with each digit
            for (int i = 0; i < res.size(); i++) {
                int prod = res.get(i) * x + carry;

                res.set(i, prod % 10);
                carry = prod / 10;
            }

            // Store remaining carry
            while (carry != 0) {
                res.add(carry % 10);
                carry /= 10;
            }
        }

        // Convert digits to required order
        Collections.reverse(res);

        return res;
    }

    public static void main(String[] args) {
        int n = 5;

        ArrayList<Integer> ans = factorial(n);

        System.out.print("[");
        for (int i = 0; i < ans.size(); i++) {
            System.out.print(ans.get(i));

            if (i + 1 < ans.size())
                System.out.print(", ");
        }
        System.out.print("]");
    }
}
Python
def factorial(n):

    # Store digits in reverse order
    res = [1]

    # Multiply by every number from 2 to n
    for x in range(2, n + 1):
        carry = 0

        # Multiply x with each digit
        for i in range(len(res)):
            prod = res[i] * x + carry

            res[i] = prod % 10
            carry = prod // 10

        # Store remaining carry
        while carry:
            res.append(carry % 10)
            carry //= 10

    # Convert digits to required order
    res.reverse()

    return res


if __name__ == "__main__":
    n = 5

    ans = factorial(n)

    print("[", end="")
    for i in range(len(ans)):
        print(ans[i], end="")

        if i + 1 < len(ans):
            print(", ", end="")
    print("]")
C#
using System;
using System.Collections.Generic;

class GFG
{
    static List<int> factorial(int n)
    {
        // Store digits in reverse order
        List<int> res = new List<int> { 1 };

        // Multiply by every number from 2 to n
        for (int x = 2; x <= n; x++)
        {
            int carry = 0;

            // Multiply x with each digit
            for (int i = 0; i < res.Count; i++)
            {
                int prod = res[i] * x + carry;

                res[i] = prod % 10;
                carry = prod / 10;
            }

            // Store remaining carry
            while (carry != 0)
            {
                res.Add(carry % 10);
                carry /= 10;
            }
        }

        // Convert digits to required order
        res.Reverse();

        return res;
    }

    static void Main()
    {
        int n = 5;

        List<int> ans = factorial(n);

        Console.Write("[");
        for (int i = 0; i < ans.Count; i++)
        {
            Console.Write(ans[i]);

            if (i + 1 < ans.Count)
                Console.Write(", ");
        }
        Console.Write("]");
    }
}
JavaScript
function factorial(n) {

    // Store digits in reverse order
    let res = [1];

    // Multiply by every number from 2 to n
    for (let x = 2; x <= n; x++) {
        let carry = 0;

        // Multiply x with each digit
        for (let i = 0; i < res.length; i++) {
            let prod = res[i] * x + carry;

            res[i] = prod % 10;
            carry = Math.floor(prod / 10);
        }

        // Store remaining carry
        while (carry) {
            res.push(carry % 10);
            carry = Math.floor(carry / 10);
        }
    }

    // Convert digits to required order
    res.reverse();

    return res;
}

// Driver code
    let n = 5;

    let ans = factorial(n);

    console.log("[" + ans.join(", ") + "]");

Output
[1, 2, 0]

[Alternative Approach] Using Linked List - O(n × d) Time and O(d) Auxiliary Space

The idea is to store each digit of the factorial in a linked list and multiply it by every number from 2 to n using manual multiplication.

A linked list can also be used to store the digits of a large factorial when the result cannot fit in standard integer data types. Each node stores one digit, and a carry is maintained while multiplying.

The digits are stored in reverse order so that the least significant digit is processed first. For example, 120 can be stored as:

2056958666

Here, 0 is the least significant digit.

Steps:

  • Create a linked list with a single node containing 1.
  • Traverse from x = 2 to n.
  • For each x, multiply it with every digit in the linked list and maintain a carry.
  • Store the last digit of the product in the current node and update the carry.
  • Create new nodes for any remaining digits of the carry.
  • Traverse the linked list and store its digits in an array, then reverse the array to obtain the factorial digits in the required order.
C++
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* next;

    Node(int x) {
        data = x;
        next = nullptr;
    }
};

void multiply(Node* head, int x) {
    Node* curr = head;
    Node* prev = nullptr;
    int carry = 0;

    while (curr != nullptr) {
        int prod = curr->data * x + carry;

        curr->data = prod % 10;
        carry = prod / 10;

        prev = curr;
        curr = curr->next;
    }

    // Store remaining carry
    while (carry) {
        prev->next = new Node(carry % 10);
        carry /= 10;
        prev = prev->next;
    }
}

vector<int> factorial(int n) {
    Node* head = new Node(1);

    // Multiply by every number from 2 to n
    for (int x = 2; x <= n; x++) {
        multiply(head, x);
    }

    vector<int> ans;

    // Store digits in reverse order
    while (head != nullptr) {
        ans.push_back(head->data);
        head = head->next;
    }

    // Convert digits to required order
    reverse(ans.begin(), ans.end());

    return ans;
}

int main() {
    int n = 5;

    vector<int> ans = factorial(n);

    cout << "[";
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i];

        if (i + 1 < ans.size())
            cout << ", ";
    }
    cout << "]";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Collections;

class Node {
    int data;
    Node next;

    Node(int x) {
        data = x;
        next = null;
    }
}

class GFG {

    static void multiply(Node head, int x) {
        Node curr = head;
        Node prev = null;
        int carry = 0;

        while (curr != null) {
            int prod = curr.data * x + carry;

            curr.data = prod % 10;
            carry = prod / 10;

            prev = curr;
            curr = curr.next;
        }

        // Store remaining carry
        while (carry != 0) {
            prev.next = new Node(carry % 10);
            carry /= 10;
            prev = prev.next;
        }
    }

    static ArrayList<Integer> factorial(int n) {
        Node head = new Node(1);

        // Multiply by every number from 2 to n
        for (int x = 2; x <= n; x++) {
            multiply(head, x);
        }

        ArrayList<Integer> ans = new ArrayList<>();

        // Store digits in reverse order
        while (head != null) {
            ans.add(head.data);
            head = head.next;
        }

        // Convert digits to required order
        Collections.reverse(ans);

        return ans;
    }

    public static void main(String[] args) {
        int n = 5;

        ArrayList<Integer> ans = factorial(n);

        System.out.print("[");
        for (int i = 0; i < ans.size(); i++) {
            System.out.print(ans.get(i));

            if (i + 1 < ans.size())
                System.out.print(", ");
        }
        System.out.print("]");
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.next = None


def multiply(head, x):
    curr = head
    prev = None
    carry = 0

    while curr is not None:
        prod = curr.data * x + carry

        curr.data = prod % 10
        carry = prod // 10

        prev = curr
        curr = curr.next

    # Store remaining carry
    while carry:
        prev.next = Node(carry % 10)
        carry //= 10
        prev = prev.next


def factorial(n):
    head = Node(1)

    # Multiply by every number from 2 to n
    for x in range(2, n + 1):
        multiply(head, x)

    ans = []

    # Store digits in reverse order
    while head is not None:
        ans.append(head.data)
        head = head.next

    # Convert digits to required order
    ans.reverse()

    return ans


if __name__ == "__main__":
    n = 5

    ans = factorial(n)

    print("[", end="")
    for i in range(len(ans)):
        print(ans[i], end="")

        if i + 1 < len(ans):
            print(", ", end="")
    print("]")
C#
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node next;

    public Node(int x) {
        data = x;
        next = null;
    }
}

class GFG {

    static void multiply(Node head, int x) {
        Node curr = head;
        Node prev = null;
        int carry = 0;

        while (curr != null) {
            int prod = curr.data * x + carry;

            curr.data = prod % 10;
            carry = prod / 10;

            prev = curr;
            curr = curr.next;
        }

        // Store remaining carry
        while (carry != 0) {
            prev.next = new Node(carry % 10);
            carry /= 10;
            prev = prev.next;
        }
    }

    static List<int> factorial(int n) {
        Node head = new Node(1);

        // Multiply by every number from 2 to n
        for (int x = 2; x <= n; x++) {
            multiply(head, x);
        }

        List<int> ans = new List<int>();

        // Store digits in reverse order
        while (head != null) {
            ans.Add(head.data);
            head = head.next;
        }

        // Convert digits to required order
        ans.Reverse();

        return ans;
    }

    public static void Main() {
        int n = 5;

        List<int> ans = factorial(n);

        Console.Write("[");
        for (int i = 0; i < ans.Count; i++) {
            Console.Write(ans[i]);

            if (i + 1 < ans.Count)
                Console.Write(", ");
        }
        Console.Write("]");
    }
}
JavaScript
class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}

function multiply(head, x) {
    let curr = head;
    let prev = null;
    let carry = 0;

    while (curr !== null) {
        let prod = curr.data * x + carry;

        curr.data = prod % 10;
        carry = Math.floor(prod / 10);

        prev = curr;
        curr = curr.next;
    }

    // Store remaining carry
    while (carry) {
        prev.next = new Node(carry % 10);
        carry = Math.floor(carry / 10);
        prev = prev.next;
    }
}

function factorial(n) {
    let head = new Node(1);

    // Multiply by every number from 2 to n
    for (let x = 2; x <= n; x++) {
        multiply(head, x);
    }

    let ans = [];

    // Store digits in reverse order
    while (head !== null) {
        ans.push(head.data);
        head = head.next;
    }

    // Convert digits to required order
    ans.reverse();

    return ans;
}

// Driver code
    let n = 5;

    let ans = factorial(n);

    process.stdout.write("[");
    for (let i = 0; i < ans.length; i++) {
        process.stdout.write(ans[i].toString());

        if (i + 1 < ans.length)
            process.stdout.write(", ");
    }
    process.stdout.write("]");

Output
[1, 2, 0]
Comment