Factorial: Infinite Loop Starting


#1





def factorial(x):
    f=1
    if x==0:
        return 0
    else:
        while x!=0:
            f=x*factorial(x-1)
    return f

What is happening wrong here? Can't figure out! Any type of help will be highly appreciated


#2

Your code causes an infinite loop because x will never become 0. Your code keeps running the while loop because x != 0 all the time. If it was, your code returns 0.

This is the code I used:

def factorial(x):
    result = 1
    for integer in range(1,x+1):
        result *= integer
    return result

#3

Plus, you got some recursion going on in the while loop. I suggest either just doing a loop or a recursion but not both (due to optimisation purposes). Even if the recursion finishes, your while loop still runs because x will never become 0 if x != 0 as an input.


#4

I have factorial calling itself, then return the factorial of the number, factorial (x - 1), while multiplying the returning the integer (x) with it.

@casz146 and @datfatcat explained what's going on in your code. I think if you took out the f=1 and put the 1 in your if statement, you can go from there and simplify your code to where I got mine.

This is what I had that passed.

def factorial(x):
    if x == 1:
        return 1
    else:
        return x * factorial(x - 1)

#5

Oh yes, the recursion approach :+1:


#6

Thanks man!
I think one more condition on if should have been added perhaps? That is when x==0?
Thanks for helping out!


#7

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