A box can only hold so much
A number in an ordinary int box can only reach about 2 billion. A box is made of a fixed number of switches, and there is nothing past the last one. If a calculation goes beyond the limit, the number wraps around, like a car's trip meter that rolls over to zero.
The result is a wrong number, and nobody tells you. Python is kind here, because its numbers grow as needed. Java and C++ are not, so you have to think about it.
- a
- 100000
- b
- 100000
Two numbers that fit comfortably in an int box.
The bigger box
The fix is to use a bigger box. Most languages have one called long, which holds numbers up to about 9 quintillion. Return a long when the answer could be huge.
There is one more trap. In Java and C++, two ints multiplied together are worked out in an int box, even if you store the answer in a long. Make one of the two numbers long first, and the multiplying happens in the big box.
# Java and C++: make one side long product = (long) a * b