Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

java - Perfect numbers. Something wrong

I am trying to accomplish a task. To print 4 perfect numbers which are between 1 and 10000.

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.

Here's my code:

public class PerfectNumbers
{
    public static void main(String[] args)
    {
        // Perfect numbers!

        for (int number = 1; number < 10000; number++)
        {
            int sum = 0;
            int i = 1;
            while (i < number)
            {

                if (number % i == 0)
                {
                    sum += i;
                    i++;

                }
                else
                {   
                    i++;
                    continue;
                }

                if (sum == number)
                {
                    System.out.println(number);
                }
                else
                {
                    continue;
                }

            }
        }
    }
}

The output is:

6
24 <--- This one is wrong because next must be 28. 
28
496
2016
8128
8190

What is wrong in my code? Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The if (sum == number) check needs to be done outside the loop. Otherwise you might pick up numbers such that the sum of a subset of divisors equals the number.

In fact, 24 is one such example since 1+2+3+4+6+8=24. Your code prematurely concludes that 24 is perfect, despite it also being divisible by 12.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...