0

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.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58

2 Answers2

3
         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)
Julien
  • 13,986
  • 5
  • 29
  • 53
-1

That's simple. 1+2+3+4+6+8=24 You should compare the sum and double of the original number after for.

tomo_iris427
  • 161
  • 6