Perfect numbers. Something wrong

无人久伴 提交于 2019-12-13 22:24:58

问题


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.


回答1:


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.




回答2:


Your code prints 24 because when you step through the loop as i = 8 the sum of all numbers is 1+2+3+4+6+8 = 24 so your condition gets met. You need to add another conditional to the print to prevent it from printing when the summation has not yet been completed. In this case you haven't yet added 12 to make the calculation valid.

I would move the if statement outside the while loop so it is checked only after your sum is calculated.



来源:https://stackoverflow.com/questions/13805335/perfect-numbers-something-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!