/* An instance of this class deems numbers whose absolute value is prime ** to be RED and others to be BLUE. */ public class PrimeVsComposite implements RedBlueClassifier { // constructor // ----------- // No constructor needed, as there are no instance variables to initialize. // methods of interest // ------------------- /* Returns true if the absolute value of the given number is prime, ** false otherwise. */ public boolean isRed(Integer num) { return isPrime(Math.abs(num)); } /* Returns true if the given number is not RED. */ public boolean isBlue(Integer num) { return !isRed(num); } // private // ------- /* Returns true iff the given number is prime. ** A number is prime iff it is positive and has exactly two ** divisors (1 and itself). ** pre: num >= 0 */ private boolean isPrime(int num) { boolean result; if (num == 2) { result = true; } else if (num == 1 || num % 2 == 0) // Neither 1 nor any even number other than 2 is prime. { result = false; } else { // num must be an odd number greater than 2. Such a number is // prime iff it has no odd divisor that is <= to its square root. // What follows is a search for such a divisor. int numSqrt = (int)(Math.sqrt(num)); int cand = 3; // candidate divisor // loop invariant: 3 <= cand <= numSqrt + 2 && // num has no divisors in [3..cand) while (cand <= numSqrt && num % cand != 0) { cand = cand + 2; } // If cand > numSqrt, num has no divisors in [3..numSqrt] and // thus is prime; otherwise cand is equal to num's smallest // nontrivial divisor, making num non-prime. result = cand > numSqrt; } return result; } }