/** An instance of this class can calculate, via its sqrt() methods, an ** approximation to the square root of a given number of type either ** long or int. ** @author R. McCloskey ** @version Feb. 2005 */ public class SquareRootCalc { /** Calculates the floor of the square root of k. ** @param k the value whose square root is to be computed. ** @pre: 0 <= k ** @return r satisfying r2 ≤ k < (r+1)2 ** @throws IllegalArgumentException in case the precondition is not met */ public long sqrt(long k) { if (k < 0) { throw new IllegalArgumentException("sqrt() requires nonnegative arg"); } // use binary search to calculate square root of k long low = 0, high = k+1, mid; // loop invariant: low^2 <= k < high^2 while (low != high-1) { mid = (low + high) / 2; // assertion low < mid < high if (mid * mid <= k) { low = mid; } else // mid * mid > k { high = mid; } } return low; } /** Calculates the floor of the square root of k. ** @param k the value whose square root is to be computed. ** @pre: 0 <= k ** @return r satisfying r2 <= k < (r+1)2 */ public int sqrt(int k) { return (int) sqrt((long) k); } }