/** * Matt Weiss * CSE 2231 * 3:00 PM */ public class Homework4 { /* Based on Integer artihmetic in the Java language, there are automatically no decimals when dealing with the division of two integers. This being the case, integers are limited by INTEGER_MAX_VALUE, a value around 2.147 billion. The average of any number of these max values will always result back to INTEGER_MAX_VALUE or lower, as can be seen with basic mathematics. The same applies for any average of an arbitrary number of INTEGER_MIN_VALUE's. */ /** * Returns the integer average of two given {@code int}s. * * @param j * the first of two integers to average * @param k * the second of two integers to average * @return the integer average of j and k * @ensures
	 * {@code average = (j+k)/2}
	 * 
*/ public static int average(int j, int k) { int signTwo = (int) Math.signum(k); int value = (j+k) / 2; int reductions = 1; //If bothOdd is true, then we need to add or subtract one at the end, //as there will be two cases where 0.5 was chopped off in the end due to integer arithmetic. boolean bothOdd = j % 2 != 0 && k % 2 != 0; //If 2nd val pos, need to check for positive overflow (can't add into a neg overflow) if (signTwo > 0) { while ((value = (j + k) / 2) <= 0) { j /= 2; k /= 2; reductions++; } if (bothOdd) value++; } //If 2nd val neg, need to check for negative overflow (can't subtract into pos overflow) else if (signTwo < 0) { while ((value = (j + k) / 2) >= 0) { j /= 2; k /= 2; reductions++; } if (bothOdd) value--; } /* * Mathematically speaking, the average of any two values, i and j, and be represented either: * (i + j) / 2 * or... * (i / 2) + (j / 2) * by the Distributive Property. * * This being the case, we can simply reduce the values */ System.out.println("Adjusting the final value of " + value + " by a factor of " + reductions); return value * reductions; } }