/* CSE 142, Autumn 2007, Marty Stepp This is a new version of our previous Factors program that uses "Boolean Zen." Boolean Zen means understanding why the following are never needed, == true == false != true != false and also understanding why the one-line version of isPrime below is the same as the previous multi-line version. */ import java.util.*; // for Scanner public class Factors4 { public static void main(String[] args) { if (isPrime(17)) { System.out.println("17 is a prime number."); } if (!isPrime(42)) { System.out.println("42 isn't a prime number."); } } // Returns whether the given integer is a prime number // (whether it has only itself and 1 as factors). public static boolean isPrime(int n) { return countFactors(n) == 2; } // Returns whether the given integer is a composite (non-prime) number. public static boolean isComposite(int n) { // return countFactors(n) != 2; // return isPrime(n) == false; return !isPrime(n); } // Returns how many factors the given number has. // Assumes n is non-negative. public static int countFactors(int n) { int count = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { // i is a factor of n count++; } } return count; } }