DSA Factory
Free lessonsProgramming basics · Stage 1 · Numbers · Step 4

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.

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
Quick check

Two ints can each be as big as 90 million. What should hold their product?

  1. AA long
  2. BAn int
  3. 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.

Your problem

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.

Example
a = 100000, b = 100000 → 10000000000

0 ≤ a, b ≤ 90,000,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding