Homework: Integer Average
Consider the following contract specification for the static method
average . Please note that, both in the specification and in the Java
programming language, the integer-division ('/') operator's result
is obtained by truncating toward zero. Hence, (-3 / 2) = -1 and
(9 / 2) = 4 . It is like "rounding", except that the quotient given as
the result is not necessarily the closest integer to the correct
rational quotient: it is the first-encountered integer closer to zero
than the correct rational quotient.
/**
* 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 average = (j+k)/2
*/
public static int average(int j, int k) {...}
Answer the following questions.
-
Provide an argument justifying the following claim: The average (as defined here) of two Java
ints is representable as anint, regardless of the lower and upper bounds on the value of anint. -
Provide an implementation of the
averagemethod withintas the only type you use (except, perhaps, forboolean). Note:return (j+k)/2;does not implement the contract specification. Some of the test cases shown below will reveal defects in this obvious implementation. Your challenge is to figure out a way or ways to work around the fact that, if a sum is non-representable as anint(has overflowed), then Java arranges that the value provided at run-time is wrong. In other words, each arithmetic operation has a precondition thatrequiresthat the result is representable in its type. Your challenge includes making sure that this precondition is always satisfied. As you find ways to do so, you'll also need to work out difficulties involved with the truncating going in the wrong direction, as compared with the truncation direction established in the contract specification. (By the way, because it is mathematics, the expressions in contract specifications always mean the right answer; in contract specifications, there is no overflow.) Each of the following is a valid test case for theaveragemethod.Test Input: j Input: k Expected Result 1. Integer.MAX_VALUEInteger.MAX_VALUE - 1Integer.MAX_VALUE -12. Integer.MIN_VALUEInteger.MIN_VALUE + 1Integer.MIN_VALUE + 13. Integer.MIN_VALUEInteger.MIN_VALUEInteger.MIN_VALUE4. Integer.MAX_VALUEInteger.MAX_VALUEInteger.MAX_VALUE5. 5866. -5-8-67. 11-438. -3209. 35410. -3-5-411. -340