Reputation: 11
I finally got the perfect number program that I am writing in Python to work...just not correctly.
I have run the code 3 times and it keeps returning 24 as a perfect number.
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)
Any advice would be welcome.
Upvotes: 0
Views: 76
Reputation: 15176
if (totalFactors == i):
print(i, end = " ")
needs to be 2 levels less since you want to check the sum totalFactors
only after all possible candidate divisors have been looked at:
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)
Upvotes: 3
Reputation: 158
That's simple.
1+2+3+4+6+8=24
You should compare the sum and double of the original number after for
.
Upvotes: -1