Hacker News new | ask | show | jobs
by altaltalt 1326 days ago
Can't it simply be written like this?

    mid = low/2 + high/2
3 comments

While that is true it is not relevant here, since this example does not involve associativity.

What is relevent here is that integer division is not distributive over addition.

Nope, try low = 1, high = 1 and you get mid = 0.
i think you can fix it with: (low >> 1) + (high >> 1) + (low & 1 & high)

for unsigned numbers. not sure if it works for signed numbers.

For low=3, high=5 case, this gives mid=3.