|
| 1 | +package com.codefortomorrow.advanced.chapter13.solutions; |
| 2 | + |
| 3 | +import java.util.Scanner; |
| 4 | + |
| 5 | +/* |
| 6 | +Write a method called isPrime which returns |
| 7 | +true if the given integer is prime and false otherwise. |
| 8 | +
|
| 9 | +This is similar to the Chapter 11 problem, but this time write |
| 10 | +your method using recursion. |
| 11 | +
|
| 12 | +In your main method, include a Scanner so the user can check |
| 13 | +as many numbers as they want until they enter -1. |
| 14 | +
|
| 15 | +Note: There are more complex solutions, but this is the fastest one |
| 16 | +within the scope of this chapter. |
| 17 | +*/ |
| 18 | + |
| 19 | +public class PrimePractice { |
| 20 | + |
| 21 | + public static void main(String[] args) { |
| 22 | + Scanner reader = new Scanner(System.in); |
| 23 | + int number = 0; |
| 24 | + while (number != -1) { |
| 25 | + System.out.print("Enter an integer to check: "); |
| 26 | + number = reader.nextInt(); |
| 27 | + if (number != -1) { |
| 28 | + if (isPrime(number, 2)) { |
| 29 | + System.out.println("That is a prime!"); |
| 30 | + } else { |
| 31 | + System.out.println("Not a prime!"); |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + reader.close(); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * isPrime checks the primality of a given integer. |
| 40 | + * @param n The integer to check |
| 41 | + * @param z Current divisor (used for recursion) |
| 42 | + * @return boolean true if prime and false if not |
| 43 | + */ |
| 44 | + public static boolean isPrime(int n, int z) { |
| 45 | + // Check base cases |
| 46 | + if (n <= 2) { |
| 47 | + return n == 2; |
| 48 | + } |
| 49 | + |
| 50 | + // If n is divisible by the current divisor, |
| 51 | + // it has a factor other than 1 and thus is |
| 52 | + // not prime |
| 53 | + if (n % z == 0) { |
| 54 | + return false; |
| 55 | + } |
| 56 | + |
| 57 | + // If z gets high enough that z > sqrt(n), then n is prime, |
| 58 | + // because factors just repeat after |
| 59 | + if (z > Math.sqrt(n)) { |
| 60 | + return true; |
| 61 | + } |
| 62 | + |
| 63 | + // If none of the above work, |
| 64 | + // keep calling isPrime recursively |
| 65 | + // with a larger divisor |
| 66 | + return isPrime(n, z + 1); |
| 67 | + } |
| 68 | +} |
0 commit comments