Click to See Complete Forum and Search --> : Guess and check algorithem help


Geralds Mod
March 13th, 2008, 04:50 PM
I need help making an algorithm that finds 2 numbers that add to a certain number and multiply to a certain number.

Something like this...
Take the numbers 9 and 18 for example.
I need 2 numbers whose sum is 9 and whose product is 18.

The numbers 6 and 3 work because 6 + 3 = 9 and 6 * 3 = 18.

So I need something kinda along the lines of:

void guess_and_check(int a, int b)
{
// finds the 2 numbers here
}


Anyone got any idea's?
I kinda got coders block.

wildfrog
March 13th, 2008, 05:58 PM
Well... some math. You start with:

I: x + y = a
II: x * y = b

and end up here:

I: y = a - x
II: x * (a - x) = b


And then you got a quadratic equation to solve:

II: -x^2 - ax - b = 0

- petter

mgrey
March 13th, 2008, 08:11 PM
-x2 + ax - b = 0;)
Alternatively, you can find number couples adding up to sum, and you can multiply them to check if they make the product. Sure this will be an over simplification of the problem. It would work if both numbers are positive, like 3 and 6, but you need upper and lower limits if negative numbers are involved.