forked from ChrisMayfield/ThinkJavaCode2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimality.java
More file actions
30 lines (26 loc) · 817 Bytes
/
Primality.java
File metadata and controls
30 lines (26 loc) · 817 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Primality{
public static void main(String[] args){
System.out.println("Is 1 prime? " + isPrime(1));
System.out.println("Is 2 prime? " + isPrime(2));
System.out.println("Is 5 prime? " + isPrime(5));
System.out.println("Is 8 prime? " + isPrime(8));
System.out.println("Is 37 prime? " + isPrime(37));
}
public static boolean isPrime(int n) {
// special case (1 is neither prime or composite, by definition)
if(n == 1){
return false;
}
int d = 2; // smallest divisor
while (d < n) {
// try dividing n by the current divisor
if (n % d == 0) {
return false;
}
// set ourselves up for the next possible divisor
d++;
}
// no factors divided evenly into n, it must be prime
return true;
}
}