我的python完美数函数返回无效数据
我终于得到了我用Python编写的完美数字程序…只是不正确 我已经运行了3次代码,它一直返回24作为一个完美的数字我的python完美数函数返回无效数据,python,numbers,perfect-numbers,Python,Numbers,Perfect Numbers,我终于得到了我用Python编写的完美数字程序…只是不正确 我已经运行了3次代码,它一直返回24作为一个完美的数字 def printPerfectNumbers(firstNum, lastNum): for i in range(firstNum, lastNum +1): totalFactors = 0 for x in range(1, i): # Checks if x is a divisor, if true, adds x t
def printPerfectNumbers(firstNum, lastNum):
for i in range(firstNum, lastNum +1):
totalFactors = 0
for x in range(1, i):
# Checks if x is a divisor, if true, adds x to totalFactors.
if(i % x == 0):
totalFactors = totalFactors + x
if (totalFactors == i):
print(i, end = " ")
printPerfectNumbers(1, 1000)
欢迎提供任何建议
if (totalFactors == i):
print(i, end = " ")
需要少2级,因为您希望仅在查看了所有可能的候选因子后才检查总和totalFactors
:
def printPerfectNumbers(firstNum, lastNum):
for i in range(firstNum, lastNum +1):
totalFactors = 0
for x in range(1, i):
# Checks if x is a divisor, if true, adds x to totalFactors.
if(i % x == 0):
totalFactors = totalFactors + x
if (totalFactors == i):
print(i, end = " ")
printPerfectNumbers(1, 1000)
这很简单。
1+2+3+4+6+8=24
您应该在修复它之后,比较原始数字的总和和两倍。非常感谢。PS:你也应该尽量使用一致的缩进。。。(例如,始终是4个空格的倍数)