/* OUTPUT: true false 2 17 41 1237 */ // This program deals with prime numbers (no factors other than 1 and itself) // and relatively prime numbers (pairs that share no common factors). public class Primes { public static void main(String[] args) { System.out.println(relativelyPrime(9, 16)); System.out.println(relativelyPrime(15, 25)); System.out.println(); System.out.println(nextPrime(2)); System.out.println(nextPrime(14)); System.out.println(nextPrime(38)); System.out.println(nextPrime(1234)); } // Returns true if the given two numbers do not have any factors in common. // 9 16 public static boolean relativelyPrime(int n1, int n2) { for (int i = 2; i <= Math.min(n1, n2); i++) { if ((n1 % i == 0) && (n2 % i == 0)) { return false; } } return true; } // Returns the next prime number that is greater than or equal to n. public static int nextPrime(int n) { /* start at n check if it is prime if so, stop if not, go to the next number */ while (!isPrime(n)) { n++; } return n; } // Returns true if the given number n is prime (has no factors other than 1 and itself). public static boolean isPrime(int n) { /* less elegant solution #1: int factors = numFactors(n); if (factors <= 2) { return true; } else { return false; } */ /* solution #2: int factors = numFactors(n); return (factors <= 2); */ // shortest solution return (numFactors(n) <= 2); } // Returns the number of factors that the given n has. public static int numFactors(int n) { // cumulative sum int count = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { // i is a factor of n count++; } } return count; } } /* System.out.println */