Inverse Factorial in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number a, we have to find n, such that factorial of n (n!) is same as a. As we know, the factorial n = n * (n - 1) * (n - 2) * ... * 1. If there is no such integer n then return -1.

So, if the input is like a = 120, then the output will be 5.

To solve this, we will follow these steps −

  • i := 0, num := 1
  • L:= a new list
  • while i < a, do
    • i := factorial of num
    • insert i at the end of L
    • num := num + 1
  • if a is in L, then
    • return the (index of a in L) +1
  • otherwise,
    • return -1

Let us see the following implementation to get better understanding −

Example

 Live Demo

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

Input

120

Output

5
raja
Updated on 23-Sep-2020 07:23:39

Advertisements