Search code examples
pythonpython-3.xfactorial

How to check if a given number is a factorial or not in Python 3


For example 24, is a factorial because:

 4 * 3 * 2 * 1 = 24

The code should take 24 as an input and the output (see below) should be if it is a factorial or not.

    return "is a factorial."
else:
    return "is not a factorial."
print("The number " + str(24) + " " + str(isFactorial(24)))

Solution

  • Simplest would be to have it backwards. Generate factorials until you find it or not. That way, you are sure always to compare integers:

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