forked from mr-sergi/Hacktoberfest-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrimality.java
57 lines (49 loc) · 1.73 KB
/
Primality.java
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.HashMap;
import java.util.Scanner;
public class Primality {
// map to store primality results
private static HashMap<Integer, Boolean> primes = new HashMap<Integer, Boolean>();
public static void main(String[] args) {
System.out.println("Enter your numbers for primality test (Type \"exit\" to stop):");
Scanner in = new Scanner(System.in);
String input = in.nextLine();
while (!input.equals("exit")) {
try {
System.out.println(isPrime(Integer.parseInt(input)));
} catch (Exception e) {
System.out.println("Enter a valid number!");
}
input = in.nextLine();
}
in.close();
}
private static boolean isPrime(int n) {
// edge case
if (n <= 1)
return false;
if (n == 2 || n == 3 || n == 5) {
primes.put(n, true);
return true;
}
// if primality for n is already calculated, return it.
if (primes.containsKey(n)) {
return primes.get(n);
}
if (n % 2 == 0 || n % 3 == 0 || n % 5 == 0) {
primes.put(n, false);
return false;
}
// check for all remaining possibilities
for (int i = 1; (30 * i - 23) <= Math.sqrt(n); i++) {
if (n % (30 * i + 1) == 0 || n % (30 * i - 23) == 0 || n % (30 * i - 19) == 0 || n % (30 * i - 17) == 0
|| n % (30 * i - 13) == 0 || n % (30 * i - 11) == 0 || n % (30 * i - 7) == 0
|| n % (30 * i - 1) == 0) {
primes.put(n, false);
return false;
}
}
// finally
primes.put(n, true);
return true;
}
}