6 ms·
You can also do x + (y - x) / 2 (starting point + distance halved), that doesn't overflow, is easy to remember, and the compiler would probably optimize it furt
by mredigonda 4y ago
You can also do x + (y - x) / 2 (starting point + distance halved), that doesn't overflow, is easy to remember, and the compiler would probably optimize it further.
- mredigonda 4y agoIndeed this overflows too! Still don't have the rights here to edit or delete the comment, sorry for the confusion! It needs a couple of extra conditions: x and y need to be uint, and y needs to be >= x (you can swap them if they are not).
- mkl 4y agoIt's not a special right, you just have to do it within 2 hours.
- planede 4y agoAnd wrong, since x=-1 and y=INT_MAX overflows.
- orlp 4y agoThis can overflow for signed integers.
- phkahler 4y agoThe subtraction could overflow.
- fyresala 4y agoWhy this could be better than (x+y)/2, since they both overflows?
- deleted 4y ago[deleted]
- jlokier 4y agoOther comments point out that can overflow for some values. However if you're doing mid-point in something like binary search where you already know y >= x AND x >= 0, then x + (y - x) / 2 is indeed a fine choice. It's a good one to remember.