简体   繁体   中英

it is a python program to find factorial of a user entered number using recursion. but it generates error “previous lines repeated 995 times”

factorial = 1
def fact(a):
    if(a==0):
        return 1
    else:
        return fact(a)*fact(a-1)
num = int(input("Enter a number : "))
print(fact(num))

it is a python program to find factorial of a user entered number using recursion. but it generates error

"previous lines repeated 995 times"

Try:

def fact(a):
    if a == 0 or a == 1:
        return 1
    else:
        return a*fact(a-1)
num = int(input("Enter a number : "))
print(fact(num))

The definition of factorial is:
n! = n * (n - 1)! and you are trying: n! = n! * (n - 1)! n! = n! * (n - 1)! , with the line fact(a)*fact(a-1)

Additionally, the variable factorial is also not required since it is unused.

The root cause of the problem is in the recursive call (fact(a) * fact(a-1))

Changing this line to (a * fact(a-1)) will fix the problem. Also, optionally, the else checking can be removed, as it is not required.

Here is the working example with the updates:

# File name:  factorial.py

factorial = 1

def fact(a):
    if( a<= 1 ):
        return 1
    return (a * fact(a-1))

num = int(input("Enter a number : "))
print(fact(num))

Output:

> python factorial.py

Enter a number : 99

933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000000000

The problem is in your factorial implementation. It should be fact(a) = a * fact(a-1)

Try:

def fact(a):
    if a == 0:
        return 1
    else:
        return a*fact(a-1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM