4 ms·
The correct way most people would write this for positive integers is: if (a < b) return a + (b - a) / 2; else return b + (a - b) / 2; This method is j
by ardel95 4y ago
The correct way most people would write this for positive integers is:
if (a < b)
return a + (b - a) / 2;
else
return b + (a - b) / 2;
This method is just more efficient (for places where it matters) as it avoids divisions and branches. But for a vast, vast majority of use-case that tiny efficiency gain doesn’t really matter.
- zimpenfish 4y agoIs that the right way around? If `a<b` then `a-b` will be negative, surely, and adding that to `a` will be moving down from `a`, not from `a` to `b`? cf https://go.dev/play/p/SgdWzzqDygn https://go.dev/play/p/SgdWzzqDygn
- ardel95 4y agoEh, that’s what I get for writing code on a cell phone. Fixed.
- glxxyz 4y agoIt can be rewritten without the test: return a - (a - b) / 2;
- Chinjut 4y agoWouldn't this still overflow when one of the values is positive, the other is negative, and their difference is sufficiently large?
- ardel95 4y agoThe tweet said unsigned ints
- Chinjut 4y agoTweet? But yes, sorry, I missed that your post said positive ints. The article was about signed ints, though.
- ardel95 4y agoOh, you are right. For some reason I thought I saw unsigned in there.
- kevin_thibedeau 4y agoC promotion rules can can convert unsigned to signed and vice versa so it still matters.
- noasaservice 4y agoyou can also do min(a,b) + (max(a,b) - min(a,b))>>1