-5

必须创建列出所有完美数字(因子之和 = 数字)1 - 1000 的程序。

  • 这是一个java类,只需要使用“for”循环

我检查了我的代码 100 次,但没有输出,我在某处遗漏了一个逻辑错误,有人可以帮我吗?

public static void main(String[] args)
{
  // variables
  int total = 0;
  final int LIMIT = 1000;

  // for loop to test all numbers 1-1000
  for(int i = 1; i <= LIMIT; i++)
  {
    // if statement
    if((i != 1) && (total == i - 1))
    {
      // prints perfect number
      System.out.println((i - 1) + " is a perfect number");
      // resets total value
      total = 0;
    }
    // gets and add factors as total
    for(int divider = 1; divider < i; divider++)
    {
      if((i % divider) == 0)
      {
        total += divider;
      }
    }
  }
}
4

6 回答 6

4

你的大问题是只有total找到一个完美的数字才会重置。如果您没有找到一个完美的数字,您将继续将下一个数字的除数添加到旧总数中。你需要重新开始每个i.

以下列方式重新排列程序应该会有所帮助:

public static void main(String[] args) {
    final int LIMIT = 1000;
    for (int i = 0; i <= LIMIT; i++) {
        // Declare total here, inside the loop, so values from previous
        // iterations are discarded.
        int total = 0;
        for (/* your code here */) {
            // add up divisors
            // your code here
        }
        // compare to i, rather than always computing the total for the
        // previous number and comparing to that.
        if (/* your code here */) {
            // print output
            // your code here
        }
    }
}
于 2014-06-09T21:06:45.147 回答
2

您应该移出total = 0;if 语句。你的总数是加起来的,永远不会被重置。

于 2014-06-09T21:04:00.127 回答
0

当您从 total=0 和 i>1 开始时,(total == i - 1) 将永远不会匹配。

于 2014-06-09T21:15:12.007 回答
0

你很亲密。只需要重新评估你的逻辑。

public static void main(String[] args) {
        // variables
        int total = 0;
        final int LIMIT = 1000;

        // for loop to test all numbers 1-1000
        for (int i = 1; i <= LIMIT; i++) {

            // gets and add factors first
            for (int divider = 1; divider < i; divider++) {
                if ((i % divider) == 0) {
                    total += divider;
                }

            }

            // then check if sum == number
            // also just print i instead of - 1
            if ((i != 1) && (total == i)) {
                // prints perfect number
                System.out.println((i) + " is a perfect number");

            }

            // alway reset when we are done with a number
            total = 0;

        }

    }
于 2014-06-09T21:15:40.030 回答
0

我建议将您的算法拆分为不同的部分,这样您就可以一次专注于较小的任务。

  1. 找出数的因数i。一种获取数字并返回其因子数组的方法。
  2. 将因素加在一起。一个简单的方法,它接受一个数组并返回它是总和。
  3. 主循环:只需检查 sum(factors(i)) == i

您可以从更简单的方法开始(提示:2 和 3),然后可能会寻找一些并非完全低效的方法来实现 1

于 2014-06-09T21:10:17.870 回答
0
 for(int i=1;i<1000;i++)
    {
        int k=0;

        for(int j=1;j<i;j++)
        {
            if(i % j==0)
            {   
                k+=j;
            }

        }
        if(k==i)
        {
            System.out.println(k);
        }
    }
于 2014-06-09T21:34:54.257 回答