Numbers have limits
Know when a number is too big for its box, and pick a bigger one. About 8 minutes.
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
Two ints can each be as big as 90 million. What should hold their product?
- AA long
- BAn int
- CEither one is fine
Show the answer
A long. The product can reach about 8 quadrillion, which is far past an int but well within a long.
Big product
Return the product of two whole numbers. The answer can be much bigger than an int can hold, so the result is a long.
a = 100000, b = 100000 → 10000000000
0 ≤ a, b ≤ 90,000,000