【问题标题】:Find Perfect Number from 1-9999. Exercise from The Art and Science of Java从 1-9999 中查找完美数字。 Java的艺术与科学练习
【发布时间】:2014-06-18 21:06:23
【问题描述】:

我试图通过找出所有除数来找到完美的数字。如果它们的总和等于数字,则打印出数字。但显然它不起作用。

import acm.program.*;

public class PerfectNumber extends ConsoleProgram{
    public void run() {
        for (int n = 1; n < 9999; n++) {                                                                    
            for (int d = 2; d < n - 1; d++) {
                //d is the potential divisor of n, ranging from 2 to n-1,// 
                //not including 1 and n because they must be the divisors.//
            if (isPerfectNumber(n,d)) 
                print(n );
        }
    }
}

//method that determines if n is perfect number.//
    private boolean isPerfectNumber(int n, int d) {
         while (n % d == 0) {
         int spd = 1;
         spd += d;
         if (spd == n) {
         return true;
         } else {   
          return false;
             }
        }
    }
}

【问题讨论】:

  • 你有什么问题?
  • 这不会运行到 9999,它将运行到 9998。使用
  • 我的方法没有返回布尔类型的结果。
  • @JackDee 这意味着 n%d 正在留下余数,它正在跳过并且什么也不返回

标签: java perfect-numbers


【解决方案1】:

查看您案例中的代码大多数情况下会返回 false。我认为您正在寻找的内容有点错误。 因为 d 小于 n,并且 n 除以 d 将始终大于 0。此外,在该循环中,您永远不会更改 d 的值。

解决方案可能是:

     public void run() {
            for (int n = 1; n < 9999; n++) 
{           spd=1;                                                         
                for (int d = 2; d <= n/2; d++) { //no need to go further than n/2
                    //d is the potential divisor of n, ranging from 2 to n-1,// 
                if(n%d==0) spd+=d; //if n divides by d add it to spd.

            }
            if(spd==n) print(n);
        }

试试这个,让我知道它是否适合你。

我在这里找到了一些很酷的东西:http://en.wikipedia.org/wiki/List_of_perfect_numbers。你应该使用这个公式更快:2^(p−1) × (2^p − 1)。您可以在 wikilink 上更好地查看公式。

【讨论】:

  • 我的错,代码有点错误,试试更新版本。我必须小于或等于 n/2 而不是更少。希望这是有道理的。
  • 是的。我知道了。这就是我要说的。
  • 还有一件事,你的意思是n除以d总是大于0? n % d == 0 检查 d 是否为除数。
  • 最初的代码是 n/d。也许我看错了。您使用的 while 循环是错误的,因为您没有在内部链接 d 的值,并且在执行结束时您强制该方法返回一个真假值。我可以向您解释为什么您的代码不起作用以及如果您愿意如何修复它。
  • 另一个问题。两个 FOR 循环是否以这种方式工作:从 1 到 9999 计数 n,并且在每个计数的 n 中,从 2 到 n - 1 计数 d。例如,如果 d 从 2 计数到 5,n 只会从 6 继续计数到 7 。 希望你能理解。因为我之前写了另一个代码,它似乎工作。谢谢。
【解决方案2】:

方法 isPerfect 应该是这样的:

public static boolean isPerfect(int number) {
    int s = 1;
    int d = number / 2;
    for(int i = 2; i <= d; i++) {
        if (number % i == 0) s += i;
    }
    return s == number;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 2010-10-09
    • 2023-03-19
    • 1970-01-01
    • 2014-04-02
    • 2021-06-03
    相关资源
    最近更新 更多