frillybob frillybob - 2 months ago 9x
Java Question

Finding average of two numbers using only ints

I need to find the average of two numbers using only an int as a data type. I cannot use the formula (x1+x2)/2 = mean because that would result in overflow if the numbers are large enough.

I found this formula

int mid = low + ((high - low) / 2);

from this thread Explanation of the safe average of two numbers.

However, this formula does not work when negative numbers are involved. Does anyone have any ideas of how to go about solving this problem? Thanks

Edit - Java


You say that you can't use the form μ=(x+y)/2, but that's basically the only way to calculate this that makes sense. You do bring up a good point about overflow, but all it takes is a bit of very basic algebra to find away around that. Remember the Distributive Property?

μ = (x + y) / 2 = x/2 + y/2

By dividing both integers by 2 before adding them, you mitigate the risk of overflowing. Try it with both values set to Integer.MAX_VALUE (though read the whole post first). So...

int avg(int x, int y) {
    return x/2 + y/2;

... should do it for you. Bear in mind, you're using ints exclusively? You're gonna have some precision issues to worry about when it comes to odd integers... for example, if you do avg(1, 1), you will get a result of 0. I'll leave accounting for and fixing that little problem to you, but this should get you on the right path.