Factorial running into an infinite loop


5. factorial

The program took too long to finish. Check your code for infinite loops and try again.

For the code to work

def factorial(x):
    f = x - 1
    s = 0
    if x <= 1:
        return x
        while x > 0:
            s += x * f
            x - 1
    return s


The addition looks a little out of place. Factorial is about sequential products.

x remains unchanged since this is only an expression, not a statement.

x = x - 1


x -= 1

If x is less than zero, it does not have a factorial. Factorial 0 and 1 are both 1.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.