[英]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.它是一个 python 程序,用于使用递归查找用户输入数字的阶乘。 but it generates error
但它会产生错误
"previous lines repeated 995 times"
“前几行重复了 995 次”
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)!
n! = n! * (n - 1)!
, with the line fact(a)*fact(a-1)
, 行
fact(a)*fact(a-1)
Additionally, the variable factorial
is also not required since it is unused.此外,变量
factorial
也不是必需的,因为它未使用。
The root cause of the problem is in the recursive call (fact(a) * fact(a-1))问题的根本原因在于递归调用(fact(a) * fact(a-1))
Changing this line to (a * fact(a-1)) will fix the problem.将此行更改为(a * fact(a-1))将解决问题。 Also, optionally, the else checking can be removed, as it is not required.
此外,可选地,可以删除else检查,因为它不是必需的。
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: 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)
应该是
fact(a) = a * fact(a-1)
Try:尝试:
def fact(a):
if a == 0:
return 1
else:
return a*fact(a-1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.