【发布时间】: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