Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

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.

Too big for the box? The number wraps round and comes out wrong.
100,000 times 100,000
a: 100000
0
b: 100000
1
a × b
2
line
a
100000
b
100000

Two numbers that fit comfortably in an int box.

Move 1 of 4

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.

Make one side long: before you multiply two big numbers.
In code
# Java and C++: make one side long
product = (long) a * b