【问题标题】:Finding an odd perfect number寻找一个奇完美数
【发布时间】:2014-06-18 20:53:00
【问题描述】:

我编写了这两种方法来确定一个数字是否完美。我的教授想让我把它们结合起来,看看是否有一个奇数。我知道没有一个(已知的),但我需要实际编写代码来证明这一点。

问题在于我的主要方法。我测试了这两种测试方法。我尝试调试,但它卡在数字 5 上,但我不知道为什么。这是我的代码:

public class Lab6
{
public static void main (String[]args)
{
  int testNum = 3;

  while (testNum != sum_of_divisors(testNum) && testNum%2 != 2)
     testNum++;

}

public static int sum_of_divisors(int numDiv)
{
  int count = 1;
  int totalDivisors = 0;

  while (count < numDiv)
     if (numDiv%count == 0)
     {
        totalDivisors = totalDivisors + count;
        count++;
     }
     else
     count++;

  return totalDivisors;
}

public static boolean is_perfect(int numPerfect)
{
  int count = 1;
  int totalPerfect = 0;

  while (totalPerfect < numPerfect)
  {
     totalPerfect = totalPerfect + count;
     count++;
  }
  if (numPerfect == totalPerfect)
     return true;
  else
     return false;
}
}

【问题讨论】:

  • 当您说“调试”时,您的意思是实际使用调试器吗?调试器应该向您显示程序卡在哪种方法中。
  • 你没有在这段代码中使用 is_perfect
  • testNum%201,绝不是 2
  • @AndrewThompson - 当您看到该编辑时,您已经完成了回滚,而不是询问 OP :) 看看 this question 我最近在 Meta 上询问过,其中针对此类问题的解决方案建议编辑确实是一个回滚。
  • @R.J 好主意!感谢您的提醒。 :)

标签: java methods numbers perfect-numbers


【解决方案1】:

制作

testNum%2 != 2

作为

testNum%2 != 0

【讨论】:

  • 如果您不介意我问,这将如何解决。模数 2 永远不等于 2 那么如何使它在 5 处停止而不是堆栈溢出?
  • @zgc7009,我不知道为什么@CoinBird 说它停在5。我相信它实际上停在6(第一个完美数字,虽然不是奇数)。
【解决方案2】:
testNum=3
while (testNum != sum_of_divisors(testNum) && testNum%2 != 2)
    testNum++;

您可能想要执行“testNum+=2”,因为您只关心奇数并将 testNum %2!=2 替换为 testNum>0 或其他停止条件。最终你的整数会溢出。

“我的教授想让我把它们结合起来,看看是否有一个奇完美数。我知道没有一个(已知的),但我需要实际编写代码来证明这一点。”

您的意思是介于 3 和 2^32-1 之间吗?不知道没有奇完美数。

【讨论】:

    猜你喜欢
    • 2011-02-08
    • 2016-08-26
    • 2012-10-01
    • 2022-11-09
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    相关资源
    最近更新 更多