-1
a = input('input a number :')
for i in range(1,int(a)):
    b=0
    for z in range(1,int(a)):
        if i == z :
            continue
        elif i%z == 0:
            print('i = ',i,'z =',z)
            b += z 
            print('b = ',b)
            if b == i:
                print(i,'is a perfect number')

My question is about that why this program gives output '24' as 'perfect number' ?

I was coding a 'perfect number finder with for loop' machine.My question is about that why this program gives output '24' as 'perfect number' ?

mousetail
  • 7,009
  • 4
  • 25
  • 45
  • 1
    Your algorithm is wrong. Iterate over all values less than `a` (or optimally less than or equal to the square root of `a`) and for each value that's a divisor of `a` add it to the sum of divisors. Finally, after the iteration is complete, compare the sum of divisors with `a`. – jarmod Nov 19 '22 at 14:40
  • Welcome to Stack Overflow. "why this program gives output '24' as 'perfect number' ?" Because `b` is equal to `i` one of the times that it's checked. Please read [ask], and [carefully study](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) what happens when the code runs; this is not a debugging service. – Karl Knechtel Nov 19 '22 at 14:59

1 Answers1

0

You are checking the sum of the divisors against the number itself inside the loop, before you finish iterating over all divisors. In the case of 24, its divisors are 1, 2, 3, 4, 6, 8, 12. But, their sum up to (and including) 8 is 1+2+3+4+6+8 = 24, so the condition b == i evaluates to true. Instead, you need to perform this check once, after the loop is finished. Also, you should only check for divisors up to i-1 (this can be improved upon mathematically to floor(i/2), but let's get the basics first), not a.

Here is a slightly cleaned up version of your code, with this correction

a = int(input('input a number :'))
for i in range(1, a):
    b=0
    for z in range(1, i):
        if i%z == 0:
            b += z
            print(f'i = {i}  z = {z}  b = {b}')
    if b == i:
        print(i,'is a perfect number')
Alex P
  • 1,105
  • 6
  • 18