0

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);
            }
        }
    }
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Thanks John. I am really grateful for corrections you gave me!! I will try to manage my question better. – Nikola Jovanovic Jan 13 '18 at 17:29
  • [What does your step debugger tell you?](http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) –  Jan 13 '18 at 17:40

1 Answers1

0

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.

whatamidoingwithmylife
  • 1,119
  • 1
  • 16
  • 35