5. Factorial


#1

Why does this code keep repeating? If x is 5, then it should do 5 * (5-1) and get 20 but why does it do it again and mulitply it by x-1 until it hits 1? Also, when I define x = 5 at the top and at the bottom I say print x, it gives 5.

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


#2

def factorial(x):
if x == 1:
return 1
else:
return x * factorial(x-1) <- ur pointing at your own definition so every time the programs come here its sent back to the begining of your def.


#3

since u sent x-1 to your own definition it will later reach 1 where you dont refer to "factorial"


#4

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

"this is the answer"


#5

That's actually a good example of recursion, is it not? The function is calling itself.


#6

and if is 0?, will come with an error. lol


#7

Wouldn't it be:
//
def factorial(x):
if x == 0:
return 1
else:
return x * factorial(x-1)
//
because factorial(0) = 1 ?


#8
def factorial(x):
    fact = 1
    for i in range(1, x + 1):
        fact = fact * i
    return fact

#9

Yes, @ali_c , factorial(0) is 1.


#10

I found a funny solution to this code:

import math

def factorial(x):
    return math.factorial(x)

#11

I see that you are using recursion. If that is the case, you always need a base case. The base case tells the resursive function when to stop.
Since factorial(0) = 1 (the base case) exist, your base case, which is:

    if x == 1:
        return 1

is wrong.
It should be

    if x == 0:
        return 1

The rest looks good.