/* File: Test2.java -- March 2018 */ package l03; /** * Tests whether a number is a perfect square using a fairly efficient * algorithm. * * @author Michael Albert * */ public class Test2 implements SquareTest{ long loops = 0; long n; public boolean isSquare(long n) { this.n = n; long low = 1, high = 1, mid = 1; loops = 0; long current = 1; while (current*current < n) { loops += 1; low = current; current *=2 ; } high = current; if (high*high == n) return true; while (high - low >= 2) { loops += 1; mid = (high+low)/2; long m2 = mid*mid; if (m2 == n) { return true; } else if (m2 < n) { low = mid; } else { high = mid; } } return false; } public String report() { return "A2 loops for input " + n + " was " + loops; } public static void main(String[] args) { long n = Long.parseLong(args[0]); SquareTest test = new Test2(); System.out.println(test.isSquare(n)); System.out.println(test.report()); } }