703452. Large Factorials

Medium

Large Factorials

Slug: large-factorials2539

Difficulty: Medium

Id: 703452

Topic Tags: Arrays, factorial, Data Structures

Company Tags: None

Summary

The problem Large Factorials is about calculating the factorials of a given range of numbers efficiently. The key concepts involved are arrays and basic arithmetic operations.

Detailed Explanation

To solve this problem, we can use an array to store the factorials up to a certain limit. We can then calculate the factorial for any number within that range by looking it up in the array. This approach reduces the time complexity of calculating large factorials from exponential to constant.

Here's a step-by-step breakdown of the solution:

  1. Create an array factorials of size n+1, where n is the maximum value for which we want to calculate the factorial.
  2. Initialize the first element of the array as 1, since the factorial of 0 and 1 is 1.
  3. Calculate the factorial for each subsequent number in the range by multiplying the current number with the previous factorial and storing it in the factorials array.
  4. To calculate the factorial of a given number within the range, simply look up its value in the factorials array.

The time complexity of this approach is O(1), since we only need to access the factorials array once to get the desired result. The space complexity is O(n), where n is the maximum value for which we want to calculate the factorial.

Optimized Solutions

Java

View on GeeksforGeeks
public class LargeFactorials {
    public static void main(String[] args) {
        int n = 20; // adjust this value as needed
        long[] factorials = new long[n+1];
        factorials[0] = 1;
        for (int i = 1; i <= n; i++) {
            factorials[i] = (long) Math.pow(i, i);
        }
        System.out.println("Factorial of 10: " + factorials[10]);
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.