Whenever I run this code to solve x-puzzles I get weird outputs that don't make sense or sometimes the program will just sit there. Occasionally, it will put out the right answer. Could you tell me why it doesn't give the right answer? (without being picky and saying I should be using another header or something similar)
I assume that in the while loop, you wish to generate new random integers each time. randint and randint2 are variables, not functions. The only call to rand() you ever make is on lines 19 and 21.
I'm not sure if this will completely solve your problem, but:
If there are no numbers within range [1, c] such that x1 * x2 = c or x1 + x2 = b, then your while loop will be infinite. I'm positive that there is a deterministic way to factor two numbers, i.e. without having to use random numbers, although I don't feel like figuring out an algorithm right now.
Also, a positive number mod anything will still give a positive number in C++.
A negative number mod anything will still give a negative number in C++.
you can make a negative random number with this trick:
randint = (rand()%c+1) * pow(-1, rand()%20); //-1 to even powers is 1, to odd is -1...
consider using the c++ random tools. I think that has a better way to do it, and is generally better across the board. And, its <ctime> and <cstdlib> ... this avoids weird problems in large programs due to namespaces.
¿what's an x-puzzle?
look at the values of x1 and x2 in each iteration of the loop.
you know how to generate random numbers in the range [a;b]
if you've got the range [a;b] and subtract `a', now your range will start with 0
if you then subtract `c', now you range starts with -c
If x1+x2=b and x1.x2=c then x1 and x2 are just the roots of the quadratic equation
x2 - b x + c = 0
Why don't you solve by quadratic formula? You can't guarantee that they are integers, so rand() won't help you.
If you have entered b and c such that there are solutions in integers, then you will find them by running through the (positive and negative) factors of c, not by using rand(). However, for most arbitrary values of b and c the solutions won't be integers.