0

This is a minor issue that I'm having in a larger program. The program is for factoring a second degree polynomial. The function below is supposed to find the factors, which is does, but let's say a=6, b=1, c=-12 so a*c=-72 and I want the two numbers that will add to 1. Instead of 9 and -8, this code gives me -9 and 8. I can't figure out why. If anyone could help me with this I would really appreciate it.

void findFactors(int a, int b, int c, int&f1, int&f2)
{
    int f;
    int i=0;
    f=-int(sqrt(abs(a*c)));
    while(f<=int(sqrt(abs(a*c))))
    {
        if(f==0)
            f++;
        if((a*c)%f==0)
        {
            f1=(a*c)/f, f2=f;
            i++;
        }

        f++;
    }

    if(f!=-int(sqrt(abs(a*c))))
    {
        f1==0, f2==0;
    }
}
2
Contributors
1
Reply
2
Views
4 Years
Discussion Span
Last Post by histrungalot
0

Its wraping around.

$ ./a.out
i(0) f1(9) f2(-8)    <------ Should have stopped here
i(1) f1(12) f2(-6)
i(2) f1(18) f2(-4)
i(3) f1(24) f2(-3)
i(4) f1(36) f2(-2)
i(5) f1(72) f2(-1)
i(6) f1(-72) f2(1)
i(7) f1(-36) f2(2)
i(8) f1(-24) f2(3)
i(9) f1(-18) f2(4)
i(10) f1(-12) f2(6)
i(11) f1(-9) f2(8)  <------ When all of the way to here
-9 8
$

Try adding a break if f1+f2 equal b. I tested it a little and looks like it works

$ ./a.out
i(0) f1(9) f2(-8)
9 -8
$

Code

void findFactors(int a, int b, int c, int&f1, int&f2)
{
    int f;
    int i=0;
    f=-int(sqrt(abs(a*c)));
    while(f<=int(sqrt(abs(a*c))))
    {
        if(f==0)
            f++;
        if((a*c)%f==0)
        {
            f1=(a*c)/f, f2=f;
            //-----------------------------------
            // Debug
            //cout << "i(" << i << ") f1(" << f1 << ") f2(" <<f2 << ")" << endl;
            //-----------------------------------
            // Break if all is well
            if ( f1+f2 == b) {
               break;
            }
            i++;
        }

        f++;
    }
    //--------------------------------------
    // Was't sure what this is for?
    if(f!=-int(sqrt(abs(a*c))))
    {
        //----------------------------------
        // Why are you using '==' here? 
        // The values of f1 and f2 will be
        // unchanged.
        f1==0, f2==0;
    }
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.