1
1
package com .codefortomorrow .advanced .chapter13 .practice ;
2
2
3
- import java .lang .Math ;
4
3
/*
5
4
Write a method called isPrime which returns
6
5
true if the given integer is prime and false otherwise.
14
13
Note: There are more complex solutions, but this is the fastest one
15
14
within the scope of this chapter.
16
15
*/
16
+
17
+ import java .lang .Math ;
17
18
import java .util .Scanner ;
18
19
19
20
public class PrimePractice {
@@ -25,21 +26,25 @@ public static void main(String[] args) {
25
26
System .out .print ("Enter an integer to check: " );
26
27
s = reader .nextInt ();
27
28
if (s != -1 ) {
28
- if (isPrime (s , 2 )) System .out .println (
29
- "That is a prime!"
30
- ); else System .out .println ("Not a prime!" );
29
+ if (isPrime (s , 2 ))
30
+ System .out .println ("That is a prime!" );
31
+ else
32
+ System .out .println ("Not a prime!" );
31
33
}
32
34
}
33
35
}
34
36
35
37
//n is the number to check, z is the current number being divided
36
38
public static boolean isPrime (int n , int z ) {
37
39
//Check base cases
38
- if (n <= 2 ) return (n == 2 ) ? true : false ;
40
+ if (n <= 2 )
41
+ return (n == 2 ) ? true : false ;
39
42
//Ternary operator used there
40
- if (n % z == 0 ) return false ;
43
+ if (n % z == 0 )
44
+ return false ;
41
45
//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 ;
46
+ if (Math .pow (z , 2 ) > n )
47
+ return true ;
43
48
44
49
//If none of the above work
45
50
return isPrime (n , z + 1 );
0 commit comments