|
| 1 | +package com.codefortomorrow.advanced.chapter13.practice; |
| 2 | +/* |
| 3 | +Write a method called isPrime which returns |
| 4 | +true if the given integer is prime and false otherwise. |
| 5 | +
|
| 6 | +This is similar to the chapter 11 problem, but this time write |
| 7 | +your method using recursion. |
| 8 | +
|
| 9 | +In your main method, include a scanner so the user can check |
| 10 | +as many numbers as they want until they enter -1. |
| 11 | +
|
| 12 | +Note: There are more complex solutions, but this is the fastest one |
| 13 | +within the scope of this chapter. |
| 14 | +*/ |
| 15 | +import java.util.Scanner; |
| 16 | +import java.lang.Math; |
| 17 | +public class PrimePractice{ |
| 18 | + public static void main(String[] args){ |
| 19 | + int s = 0; |
| 20 | + while(s != -1){ |
| 21 | + Scanner reader = new Scanner(System.in); |
| 22 | + System.out.print("Enter an integer to check: "); |
| 23 | + s = reader.nextInt(); |
| 24 | + if(s != -1){ |
| 25 | + if(isPrime(s,2)) |
| 26 | + System.out.println("That is a prime!"); |
| 27 | + else |
| 28 | + System.out.println("Not a prime!"); |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + //n is the number to check, z is the current number being divided |
| 33 | + public static boolean isPrime(int n, int z){ |
| 34 | + //Check base cases |
| 35 | + if(n <= 2) |
| 36 | + return (n == 2) ? true : false; |
| 37 | + //Ternary operator used there |
| 38 | + if(n % z == 0) |
| 39 | + return false; |
| 40 | + //If z gets high enough that z > sqrt(n), then n is prime, because factors just repeat after |
| 41 | + if(Math.pow(z,2) > n) |
| 42 | + return true; |
| 43 | + |
| 44 | + //If none of the above work |
| 45 | + return isPrime(n, z + 1); |
| 46 | + } |
| 47 | +} |
0 commit comments