【发布时间】:2015-06-16 13:41:56
【问题描述】:
完美数是等于其所有正除数之和的数,不包括它自己。
对于我的家庭作业,我正在尝试编写一个程序来查找 10000 以下的所有四个完美数字,但是当我运行它时我的代码不起作用,我不确定为什么(它只运行了一秒钟或二,然后在不打印任何内容后说“构建成功”)。我将它包括在下面,以及一些解释我的思维过程的 cmets。有人可以帮我看看有什么问题吗?
public class HomeworkTwo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//Variable declaration
int n;
int possibleFactor;
int factorSum=0;
/**For each n, the program looks through all positive integers less than n
and tries to find factors of n. Once found, it adds them
together and checks if the sum equals n. Then it repeats till n=9999. **/
for (n=2; n<10000; n++) {
for (possibleFactor = 1; possibleFactor < n; possibleFactor++) {
if (n % possibleFactor == 0) {
factorSum = possibleFactor + factorSum;
}
//Is the number perfect? Printing
if (factorSum == n) {
System.out.println(""+ n +" is a perfect number.");
}
}
}
}
}
【问题讨论】:
-
我认为你需要在外循环完成每次迭代后创建
factorSum =0。
标签: java netbeans perfect-numbers