Detect if number is factorial recursively

Viewed 95

Need to create a function to evaluate if a specific number is factorial, or not.

For that I've built the following, and it is working

def is_factorial(n):
    i = f = 1
    while f < n:
        i += 1
        f *= i
    return f == n

However, now I need to make it recursive, but I am struggling with it.

So far I've managed to do the following

def isFactorial(m):
    def factorial(x):
        if x == 0:
            return 1
        else:
            return x * factorial(x - 1)
    
    if m == 1:
        return True 
    elif m == 720:
        return True
    else:
        factorialnumbers = []

Appreciate any help.

Edit: Apologies, but I forgot to specify that the function should take as input one integer only.

2 Answers
def is_factorial(n, i=1):
    n = n/i
    if n == 1:
        return True
    if n < 1:
        return False
    i += 1
    return is_factorial(n, i)


print(is_factorial(24))

you can do

def isfact(m,n):
  def fact(n):
      if n==1 or n==0:
          return 1
      else:
          return n*fact(n-1)
  if fact(n) == m:
      return True
  else:
      return False
Related