I'm currently trying to implement range checking and overflow/underflow checking for multiplication and division, but... it's more complicated than addition and subtraction.

My current way is somewhat messy.

If we assume that a custom range is set to:

Min: 0

Max: 100 000

And we have the number 15 and want to multiply by 10 000, we would get 150 000, which is above > 100 000 and thus would result in overflow and a number that is 50 000 afterwards.

The problem is that checking if Result > upper bound is not always feasible, since for example, if the upper bound is the maximum range for a 64-bit integer. The result would be an overflow, so I can't do it that way. This suggests another way.

Using mathematics, I came up with:

Min: 0

Max: 100 000

Base: 15

Multiply By: 10 000

100 000 / 15 = 6666

(Divide upper range with the current number stored (m_Data). Basically see how many times we can multiply this number with until we hit the upper bound. Also truncate to integer.)

6666 >= 10 000

(Check if the number we can multiply with is larger or equal to the amount we want to multiply with. If the result is true, then we will have no overflow.)

If true, no overflow

(If no)

10 000 - 6666 = 3334

(Get the remaining amount to multiply with that would exceed the upper bound.)

15 * 6666 = 99 990

(Multiply the current number with the maximum number we can multiply by that does not exceed the upper bound.)

100 000 - 99 990 = 10

(Calculate the difference between the maximum number and the result of the current operation. This is to take into account the lost digits due to the integer truncation.)

15 * 3334 = 50 010

(Multiply the number by the amount that exceeded the upper bound.)

50 010 - 10 = 50 000

(Subtract the difference due to the integer truncation.)

Since floating point numbers aren't reliable, I chose to do integer math instead.

But this is a pretty long way of doing it and it doesn't even take into account negative numbers on either side!

There must a better way to do it (big precision library to handle bigger numbers?) or a way to modify the algorithm or whatever to call it to work with negative numbers.

This is only for multiplication, as well. Then I'd have to implement a similar method for division. So I'm looking for insight into the matter.

Anything that might help would be nice.