Do you know what is the difference between (a+b)/2 and a+(b-a)/2?
if not, then don’t worry. Here I’m with a good explanation. Mathematically it seems to be the same.
But in programming, you might get weird results. Let’s take an example.
int a = 1000000000;
int b = 2000000000;
As we can see that (a+b)/2 is giving me -647483648 and a+(b-a)/2 is giving me 1500000000 i.e correct.
Why is this happening?
Since integers can store a maximum value of 2³¹ -1 (2147483647) in java. After that, it will go to the negative side. If you will do a+b first it will cross the integer limit and it will give you a negative result. But if you will do b-a(will be smaller) first and divide it by 2 ( will get much smaller ) and then add a.
int a = 2000000000;
int b = 1000000000;
We should always use a+(b-a)/2 instead of (a+b)/2.
If you like this article and found it interesting and knowledgeable, do hit the 👏 button and share it with your colleagues and friends.