Comment

Comment by noasaservice

I've used

min(x, y)+( ((unsigned int)abs(x-y))>>1);

with no issue.

abs(x-y)is the distance between points x and y. We don't care about order here because of the absolute value. And by its nature, it will always be positive - hence unsigned.

We divide the distance between the points by 2. This always provides a solution that fits in the signed bounds of X and Y once you add to min(x,y).

And it costs an ABS, a subtract, a non-negative bitshift, and a min().

To make it more complete, a switch statement depending on type of input function would be needed to handle the various sizes of numbers. And then it'd be doing the same but for long int->unsigned long int etc.

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton