Two billion plus two billion
transcript
Add up two balances. Each one is two billion. The program prints a negative number. It looks like a bug in the language.
A thirty-two-bit int stops a little above two billion. The true total is four billion. The int wraps around to minus two hundred and ninety-four million.
Nothing crashes, and nothing warns you. The program quietly returns a wrong total. The samples are small, so they all pass.
The fix is the type, not the algorithm. An int wraps past two billion. A long holds numbers up to nine quintillion.
In Java, declare the total as long. In C plus plus, use long long. Python never overflows, so there is nothing to do.
Read the limits before the story. A total of up to ten to the twelve needs sixty-four bits. So does a count times a large value.
Check the limits first. Then use a 64-bit total, always. Full breakdown in the lecture.