Search code examples
pythonrecursionfactorial

Factorial function producing wrong results


I know that there are more than one way of calculating the factorial of an integer as well as there is a math module. However I tried to put together a simple function that is returning a wrong result. I would love to know what went wrong here. Such as if I pass 2 as parameter it returns 3, if 3 it returns 8.

>>>def factorial(n):

        if n > 0:
            result = n * n-1
            factorial(n-1)
            return result 

>>>factorial (2)

   3

How can I fix this?


Solution

  • There are a couple of things wrong with your function:

    • You don't return anything if the condition n > 0 is false.
    • n * n-1 calculates (n * n) - 1, you probably intended n * (n - 1)
    • You call factorial recursively, but then don't do anything with the result. Currently your code acts just like if you had only written return n * n - 1 inside the if.