Perfect number table below 9999, does not show correct?

When I run eclipse the result it shows me are

0
6
28
240
496
1344
8128

The expected results are:

6
28
496
8128

Why does my code print 0, 240, and 1344?

import acm.program.*;

public class Chapter5Exercise11isPerfect extends ConsoleProgram{
    public void run (){
        for (int i = 1; i <= 9999; i++){
            int k = 0;
            for (int s = 1; s <=i/2; s++){
                if (i%s ==0){
                    k=k+s;
                }
            }
            if (k%i==0){
                println (k);
            }
        }
    }
}

1 answer

  • answered 2018-01-13 17:34 Edin Mujakic

    Well it's very simple, from Wikipedia:

    In number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself) i.e. σ1(n) = 2n.

    Your condition is wrong:

    if (k%i==0)
    

    You need to check if k and i are equal:

    if (k == i)
    

    Change that in your code and let me know if it works.