#27 · Numbers

Find the bug · #27 · Numbers Medium C++

A bulk order has a negative total

Small orders are fine, but a big bulk order comes out with a negative total.

On this page

The report

Bug report

A wholesale shop stores prices in paise. Normal orders are fine, but a bulk order of 10,000 units at ₹2,500 each shows a negative total, and the payment page refuses it.

The code

Read it first: what should it do? Then click the line where you think the bug is.

C++Click the line you think is wrong
// The order total in paise: the price of one item (in paise) times the quantity.
long long orderTotal(int pricePaise, int quantity) {
    int total = pricePaise * quantity;
    return total;
}

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
cout << orderTotal(49900, 3) << endl;
cout << orderTotal(250000, 10000) << endl;

It prints

149700
-1794967296

It should print

149700
2500000000
Show the answer: the bug, the fix, and how you’d find it

The bug (line 3)

Line 3 multiplies two ints and keeps the result in an int. 250,000 × 10,000 is 2.5 billion, more than an int can hold (about 2.1 billion), so it overflows. Signed overflow is undefined behaviour in C++; in practice it wraps around to a negative number. The function returns a long long, but by then it’s too late: the multiplication itself has to happen in 64 bits.

The fix

1// The order total in paise: the price of one item (in paise) times the quantity.2long long orderTotal(int pricePaise, int quantity) {3    int total = pricePaise * quantity;3    long long total = (long long)pricePaise * quantity;4    return total;5}

How you’d find it

  1. Reproduce with the reported order: 250,000 paise × 10,000 gives a negative number. A small order is fine.
  2. Correct for small numbers and nonsense for big ones: that’s overflow. Compare the result with the int limit, 2,147,483,647.
  3. Find where the big number is made: pricePaise * quantity, int times int, stored in an int.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

CHECK(orderTotal(250000, 10000) == 2500000000LL);
CHECK(orderTotal(1, 1) == 1);

Where else this bites

  • Java’s int wraps silently too; Math.multiplyExact throws instead.
  • In DSA, a * b % mod with ints overflows before the % happens.
Your progress stays on this device.