我试图通过找出所有除数来找到完美的数字。如果它们的总和等于数字,则打印出数字。但显然它不起作用。
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;
}
}
}
}