Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mid value of two integers

What is the difference between

int x = (right + left) / 2;

and

int x = left + (right - left) / 2;

just I got time limit exception in first case and got accepted in second case when doing binary search

like image 341
Madi Sagimbekov Avatar asked Dec 25 '15 20:12

Madi Sagimbekov


2 Answers

The sum of your int variables

right + left (out of integers limit)

is too big and exceeds integers storage limit that's why there was an over flow because of the sum, but when you use the difference version the second one

left + (right - left) (within integers limit)

it suits the calculation and is in favor of the machine.

like image 146
Tayyab Kazmi Avatar answered Sep 26 '22 11:09

Tayyab Kazmi


The int limit(bound) is 2,147,483,647.

Your right+left value is out of bound of int.
But left + (right - left) / 2 value is less than int bound, so that is why second expression works fine.

if you adding such big numbers, use long.

like image 31
Azat Nugusbayev Avatar answered Sep 24 '22 11:09

Azat Nugusbayev