|
1 | 1 | package com.codefortomorrow.advanced.chapter13.practice;
|
| 2 | + |
| 3 | +import java.lang.Math; |
2 | 4 | /*
|
3 | 5 | Write a method called isPrime which returns
|
4 | 6 | true if the given integer is prime and false otherwise.
|
|
13 | 15 | within the scope of this chapter.
|
14 | 16 | */
|
15 | 17 | 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 |
| - } |
| 18 | + |
| 19 | +public class PrimePractice { |
| 20 | + |
| 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)) System.out.println( |
| 29 | + "That is a prime!" |
| 30 | + ); else System.out.println("Not a prime!"); |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + //n is the number to check, z is the current number being divided |
| 36 | + public static boolean isPrime(int n, int z) { |
| 37 | + //Check base cases |
| 38 | + if (n <= 2) return (n == 2) ? true : false; |
| 39 | + //Ternary operator used there |
| 40 | + if (n % z == 0) return false; |
| 41 | + //If z gets high enough that z > sqrt(n), then n is prime, because factors just repeat after |
| 42 | + if (Math.pow(z, 2) > n) return true; |
| 43 | + |
| 44 | + //If none of the above work |
| 45 | + return isPrime(n, z + 1); |
30 | 46 | }
|
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 | 47 | }
|
0 commit comments