FACTORIAL, I passed this but still some confusions


#1

I passed this FACTORIAL exercise using the following code but I have some confusion.

Here,
let;s suppose the number is 5. Now, the factorial of 5 should print 5 * 4 * 3 * 2 * 1. But if we look at the code it only prints 5 * 4. [x * ( x -1)]
How did I still passed the test. Is there anything that I need to understand.
Thank you.


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

Replace this line with your code.


#2

But if we look at the code it only prints 5 * 4. [x * ( x -1)]

That is not true. For 5 it returns factorial(4) * 5. And factorial(4) is factorial(3) * 4, etc...

factorial(5) =
factorial(4) * 5 =
factorial(3) * 4 * 5 =
factorial(2) * 3 * 4 * 5 =
factorial(1) * 2 * 3 * 4 * 5 =
1 * 2 * 3 * 4 * 5 =
120

This technique is called recursion. Wikipedia has a great article about it -> https://en.wikipedia.org/wiki/Recursion


#3

thank you very much.


#4

You're very welcome :slight_smile:


#5

Bonus marks if you can now come up with an iterative approach that does not use recursion. In truth, it will turn out to be much faster, especially for larger numbers.


#6

here it is, and it worked.

def factorial(x):
    fact=1
    count =1
    while (count <=x):
        fact=fact*count
        count = count + 1
    return fact

#7

Since fact is already set to 1, this could start at 2. The loop only runs if x is 2 or more.

Something else to consider is negative inputs. Negative numbers do not have a factorial. We can filter negatives, or force positivity. I'll go with the latter since it fits your code like a glove.

while (count <= abs(x)):

#8

After reading this thread I was very curious about how to use Recursion. After searching the web I found this video that gives a good explanation on how the system actually analyzes and process a recursion function. Hope it helps you guys: https://www.youtube.com/watch?v=ozmE8G6YKww&spfreload=10


#9

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