This answer is based on the accepted answer to this question on math.stackexchange:
https://math.stackexchange.com/questions/354625/how-to-compose-given-add-sub-mult-div-functions-to-map-an-integer-m-to-n
Given the six inputs (a, b, c, d, M, N)
- a: the number we can add
- b: the number we can subtract
- c: the number we can multiply
- d: the number we can divide
- M: start number
- N: end number
I assume that they are all integers, and a> 0, b> 0, c can be positive or negative, d is not equal to 0.
Then there is a way to convert M to N by applying add, sub, mult, div,
if and only if
there are integers m and n such that

So, the first thing to do is find the greatest common factor a and b (I recommend the Euclidean algorithm as described here . Call gcd "g".
The mod is applied to both sides to verify equality.
So, start making a list of possible values ββthat the left side can take for different m:
(M * (Pow (c, m)))% g
Then start making a list of possible values ββthat the right side may have for different n:
(N * (Pow (d, n)))% g
You want to start m and n to zero and start your way up.
In the end, both sides will begin to repeat themselves, since you are using mod.
If at any time you find a match, that is, the left side is equal to some right side, return 1.
Otherwise, if you have exhausted all the values ββof the left hand and the right values, without coincidence, return 0.
Note that the mod (%) operator in C ++ behaves differently for negative numbers than the math described above. You will need to adjust the results of the mod always in the range 0 <= result <g
Finally, this only works in cases where division acts in accordance with ordinary mathematics, i.e. 3/2 = 1.5 etc.
In your case, you need to slightly modify the formula to accept integer division. In particular, the right side of the equation deals with division. Be that as it may, how the following equation works, we can make a difference, move it to the other side and multiply.
x / 3 = 1
x = 1 * 3
You will need to allow rhs to take multiple values ββeach time you power on d. For example, in the above example, we need to allow 1 * 3 equal to 3.4 or 5.
So, if d = 3, then
- Pow (d, 0) = 1.
- Pow (d, 1) = 3 or 4 or 5.
- Pow (d, 2) = 9 or 10 or 11 or 12 or 13 or 14 or 15 or 16 or 17
You will see that 9 = 3 * 3, 12 = 4 * 3 and 15 = 5 * 3. Thus, the template should be easily replicated even for different values ββof d.
I have not tried this last part, so I'm not quite sure that this covers all cases of integer division exactly, but I think it is, although it is rather tedious.