|
18 | 18 | import java.util.Scanner;
|
19 | 19 |
|
20 | 20 | public class PrimePractice {
|
21 |
| - public static void main(String[] args) { |
22 |
| - int s = 0; |
23 |
| - while (s != -1) { |
24 |
| - Scanner reader = new Scanner(System.in); |
25 |
| - System.out.print("Enter an integer to check: "); |
26 |
| - s = reader.nextInt(); |
27 |
| - if (s != -1) { |
28 |
| - if (isPrime(s, 2)) |
29 |
| - System.out.println("That is a prime!"); |
30 |
| - else |
31 |
| - System.out.println("Not a prime!"); |
32 |
| - } |
| 21 | + |
| 22 | + public static void main(String[] args) { |
| 23 | + int s = 0; |
| 24 | + while (s != -1) { |
| 25 | + Scanner reader = new Scanner(System.in); |
| 26 | + System.out.print("Enter an integer to check: "); |
| 27 | + s = reader.nextInt(); |
| 28 | + if (s != -1) { |
| 29 | + if (isPrime(s, 2)) System.out.println( |
| 30 | + "That is a prime!" |
| 31 | + ); else System.out.println("Not a prime!"); |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + //n is the number to check, z is the current number being divided |
| 37 | + public static boolean isPrime(int n, int z) { |
| 38 | + //Check base cases |
| 39 | + if (n <= 2) return (n == 2) ? true : false; |
| 40 | + //Ternary operator used there |
| 41 | + if (n % z == 0) return false; |
| 42 | + //If z gets high enough that z > sqrt(n), then n is prime, because factors just repeat after |
| 43 | + if (Math.pow(z, 2) > n) return true; |
| 44 | + |
| 45 | + //If none of the above work |
| 46 | + return isPrime(n, z + 1); |
33 | 47 | }
|
34 |
| - } |
35 |
| - |
36 |
| - //n is the number to check, z is the current number being divided |
37 |
| - public static boolean isPrime(int n, int z) { |
38 |
| - //Check base cases |
39 |
| - if (n <= 2) |
40 |
| - return (n == 2) ? true : false; |
41 |
| - //Ternary operator used there |
42 |
| - if (n % z == 0) |
43 |
| - return false; |
44 |
| - //If z gets high enough that z > sqrt(n), then n is prime, because factors just repeat after |
45 |
| - if (Math.pow(z, 2) > n) |
46 |
| - return true; |
47 |
| - |
48 |
| - //If none of the above work |
49 |
| - return isPrime(n, z + 1); |
50 |
| - } |
51 | 48 | }
|
0 commit comments