我正在尝试添加用户提供的数字的所有因子。例如,如果用户输入 5,则输出应为:“5 的因数之和为 6”。 我不知道如何添加这些数字。这是我尝试过的:
int i = 1;
int count = 0;
int sum = 0;
while(i <= num)
{
sum = i + 1;
if(num % i == 0)
{
System.out.println(i + " is a factor of "+num+".");
count++;
}
i++;
}
System.out.println(num+" has "+count+" factors.");
System.out.println("The sum of all of the factors of "+num+" is "+sum);
最佳答案
您的代码中存在逻辑错误。基本上,您每次通过循环都会重置总和,而不是将这些因子累积起来以获得运行总计。因此,在循环的最后一次迭代中,您将得到最后检查的数字加一。要修复该错误,请删除此行:
sum = i + 1;
并在 if
条件中添加此行:
sum += i;
代码应如下所示:
int i = 1;
int count = 0;
int sum = 0;
while(i <= num)
{
if(num % i == 0)
{
System.out.println(i + " is a factor of "+num+".");
count++;
sum += i;
}
i++;
}
System.out.println(num+" has "+count+" factors.");
System.out.println("The sum of all of the factors of "+num+" is "+sum);
我刚刚验证了 n=5
的输出是:
1 is a factor of 5.
5 is a factor of 5.
5 has 2 factors.
The sum of all of the factors of 5 is 6
但是 5 是质数。这是一个包含更多因素的更有趣的示例:n=8
:
1 is a factor of 8.
2 is a factor of 8.
4 is a factor of 8.
8 is a factor of 8.
8 has 4 factors.
The sum of all of the factors of 8 is 15
注意:您的算法可以优化。提示:当您找到一个因子时,您可以通过将输入的数字除以它来轻松确定另一个因子。我将其余的优化留给您作为练习。享受吧!
关于java - 添加多个用户输入的因素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35352841/