The middle that went negative.
transcript
A search over two billion numbers. The middle came out negative. The code looked fine. The sum was the problem.
Lo is one and a half billion. Hi is two billion. The sum is three and a half billion. A thirty-two bit integer stops near two point one billion. In Java, the sum wraps negative. Half of that, taken after the wrap, is negative too.
The first form adds two big numbers. The second subtracts first. Hi minus lo is five hundred million. Half of it added to lo is safe.
For positions in a list, you need over a billion items. For a search over answers, two billion is easy to reach. Bytes and milliseconds both get there. The safe form costs nothing.
Java and C plus plus overflow, with thirty-two bit ints. JavaScript sums are exact up to two to the fifty-three. A shift wraps at thirty-two bits. Python integers never overflow. One habit is safe everywhere.
Write lo plus half of hi minus lo. Full breakdown in the lecture.