因此,我正在编写一种方法,该方法接受用户输入并打印其所有主要因素。它有效,只是它在每个列表的末尾给了我一个负数。这是什么原因造成的??
static void PrimeFactors(int userInput)
{
// create a variable which is a new version of userInput that can be manipulated by the method
int input = userInput;
// declare a new list which will contain all of the factors of the user input.
var factors = new List<int>();
// While the input is greater than 1, if input mod counter is equal to 0,
// add counter to factor list and set input value to input / counter
// if input % counter != 0, break and start the for loop again
for(int counter = 1; input >= 1; )
{
if(input % counter == 0)
{
factors.Add(counter);
input = input / counter;
counter++;
}
else
{
counter++;
}
}
// display the prime factors
foreach (int factor in factors)
{
Console.Write($"{factor} ");
}
}
当我输入 90 时,我得到 1, 2, 3, 5, -3。当我输入 31 时,我得到 1, 31, -1。当我输入500时,输出是1,2,5,10,-5。你明白了。
我知道我的代码在仅过滤素数方面并不完整,但我想在改进之前解决这些负数,以确保只有素数进入列表。
问题来自这一行:
if(input % counter == 0)
如果输入 = 31 且计数器 >= 32 => 输入 % 计数器始终不等于 0。计数器会增加,直到溢出并翻转到最小数字。例如:
int a = int.MaxValue;
int b = 1;
int c = a + b; // c will be -2147483648