完美数字是一个数字,等于所有正数除数的总和,不包括在内。
对于我的作业,我试图编写一个程序来查找10000以下的所有四个完美数字,但是当我运行它时我的代码不起作用而且我不确定为什么(它只运行一两秒,然后说#34;建立成功"没有打印任何东西)。我将其包括在内,以及一些解释我思考过程的评论。有人可以帮助我,并告诉我它有什么问题吗?
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.");
}
}
}
}
}
答案 0 :(得分:3)
您在第一个factorSum
循环之前将0
初始化为for
,但在尝试每个新0
时,您不会将其重置为n
。这些因素不断增加,并且永远不会与要检查的数量相等。在0
n
循环的开头将其重置为for
。
此外,您可能希望在内部for
循环之后但在外部for
循环结束之前移动测试并打印数字为完美数字,否则它可能会打印超过必要的。
答案 1 :(得分:1)
您的程序存在一些问题:
factorSum
重置为0
factorSum == n
,而不是在循环内部。n/2
;例如10永远不会被7整除。这是生成的程序(格式稍微好一些):
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++) {
factorSum = 0;
for (possibleFactor = 1; possibleFactor <= n / 2; possibleFactor++) {
if (n % possibleFactor == 0) {
factorSum = possibleFactor + factorSum;
}
}
// Is the number perfect? Printing
if (factorSum == n) {
System.out.println("" + n + " is a perfect number.");
}
}
}
}
答案 2 :(得分:1)
我想你已经做到了,但无论如何,代码中的主要问题是“factorSum”变量。检查每个数字后,应再次将其设置为0。另外,我用printf代替println,但它是一样的:
public static void main(String[] args) {
int number = 0;
int factor = 0;
int factorSum = 0;
for(number = 2; number < 10000; number++) { //for each number we will check the possible factors.
factorSum = 0;
for(factor = 1; factor < number; factor++)
if((number % factor) == 0) { //if it is a factor, we add his value to factorSum.
factorSum = factorSum + factor;
}
if(factorSum == number) {
System.out.printf("The number: %d is a perfect number.\n", number);
}
}
}
答案 3 :(得分:0)
你应该保持这样
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;
}