WB CS student
WB CS student

Reputation: 11

My python perfect number function returns invalid data

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

Answers (2)

Julien
Julien

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

tomo_iris427
tomo_iris427

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

Related Questions