如何用总和获得正产品的负面因素

how to get the negative factors of a positive product with a sum

本文关键字:何用总      更新时间:2023-10-16

我可能在标题中没有很好地解释这一点,因为我真的不知道如何用标题的长度来解释它,所以我为此道歉。无论如何,这是我当前的代码:

// Gets the product that is used to get the factors
cout << "Enter a number that you want to be factored" << endl;
cin >> y;
system("cls");
// Gets the sum from the user that the two factors need to add up to
cout << "Input the sum that is needed" << endl;
cin >> neededSum;
secondary = y;
system("cls");
// Lists the factors that add up to the specified sum
cout << "The numbers that add up to " << neededSum << " are:" << endl;
for (int i = 0; i < 100; i++)
{
    x++;
    increment++;
    y = secondary / x;
    product = x * y;
    if (product == secondary)
    {
        sum = x + y;
        if (sum == neededSum)
        {
            cout << x << " and " << y << endl;
        }
    }
}

基本上,它需要一个产品列出该产品的所有因素。然后,它将所有因素相加,直到找到加起来等于指定总和的因子。

但是,如果指定的总和是负数,例如"-11",它将不起作用,因为"28"(示例)的因数是 4 和 7,而不是 -4 和 -7。我需要找到一种方法来解决这个问题,以便它知道何时必须是 -4 和 -7 而不是正反向。

提前感谢您的帮助。

假设 x 和 y 是负数:

if (product == secondary)
{
    sum = x + y;
    if (sum == neededSum)
    {
        cout << x << " and " << y << endl;
    }
    else if (-sum == neededSum)
    {
        cout << -x << " and " << -y << endl;
    }
}