Factorials... please help


#1



Hello. After doing some research I was able to complete the lesson. It left me confused though. I don't know if I missed something or what. Can someone please help me to understand why the code below works. When I read it "logically" with an input of 4, I come up with 12. Why does it work to achieve the correct answer of 24. Does the If/else statement keep running through until it gets to 0? If someone could help me understand it that would be great.

It probably sounds like a noob question, but its probably because I am!


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


#2

factorial(4) = 4 * factorial(3) = 24
factorial(3) = 3 * factorial(2) = 6
factorial(2) = 2 * factorial(1) = 2
factorial(1) = 1 * factorial(0) = 1
factorial(0) = 1

#3

The recursive technique is a bit more advanced than we should have learned to this point. May I suggest trying to write an iterative method for this problem so you get the practice.

Given x is 4.

// x == 0?
no
return 4 * factorial(3)
// x == 0?
no
return 3 * factorial(2)
x == 0?
// no
return 2 * factorial(1)
x == 0?
// no
return 1 * factorial(0)
x == 0?
// yes
return 1 * 1 * 2 * 3 * 4
// 24

#4

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