Inverse Factorial in Python

An inverse factorial problem asks us to find which number n produces a given factorial value. Given a number a, we need to find n such that n! = a. If no such integer exists, we return -1.

For example, if a = 120, we need to find n where n! = 120. Since 5! = 5 × 4 × 3 × 2 × 1 = 120, the answer is 5.

Algorithm

To solve this problem, we follow these steps ?

  • Initialize i = 0 and num = 1
  • Create an empty list L to store factorial values
  • While i , do:
    • Calculate i = factorial(num)
    • Append i to list L
    • Increment num by 1
  • If a is found in L, return index + 1
  • Otherwise, return -1

Implementation

import math

class Solution:
    def solve(self, a):
        i, num = 0, 1
        factorials = []
        
        while i < a:
            i = math.factorial(num)
            factorials.append(i)
            num += 1
            
        if a in factorials:
            return factorials.index(a) + 1
        else:
            return -1

# Test the solution
ob = Solution()
print(ob.solve(120))
print(ob.solve(24))
print(ob.solve(100))  # Not a factorial
5
4
-1

Optimized Approach

Instead of storing all factorials, we can check each factorial as we calculate it ?

import math

def inverse_factorial(a):
    if a == 1:
        return 1
    
    n = 1
    factorial = 1
    
    while factorial < a:
        n += 1
        factorial *= n
        
    return n if factorial == a else -1

# Test cases
test_values = [1, 6, 24, 120, 100, 720]
for val in test_values:
    result = inverse_factorial(val)
    print(f"Inverse factorial of {val}: {result}")
Inverse factorial of 1: 1
Inverse factorial of 6: 3
Inverse factorial of 24: 4
Inverse factorial of 120: 5
Inverse factorial of 100: -1
Inverse factorial of 720: 6

How It Works

The optimized approach calculates factorials incrementally:

  • 1! = 1
  • 2! = 1 × 2 = 2
  • 3! = 2 × 3 = 6
  • 4! = 6 × 4 = 24
  • 5! = 24 × 5 = 120

We stop when we either find the target value or exceed it. This approach is more memory-efficient as it doesn't store all factorial values.

Conclusion

The inverse factorial problem can be solved by incrementally calculating factorials until we find the target value or determine it doesn't exist. The optimized approach using iterative multiplication is more efficient than storing all factorial values in memory.

---
Updated on: 2026-03-25T10:26:11+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements