-
Notifications
You must be signed in to change notification settings - Fork 3
/
12.SuperProgrammerGod.java
74 lines (60 loc) · 1.91 KB
/
12.SuperProgrammerGod.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/// Execution time is more important than memory consumption.
/// And if you can do some preprocessing, then you should.
/// Thus, for smaller integers you have reduced the complexity
/// from √n to 1.
public class PrimeNumberChecker {
public static final int MAX_MEMORY_SPACE = 64000000;
public static final int MIN_MEMORY_SPACE = 4;
private boolean[] primeNumberMarks;
public PrimeNumberChecker() {
this(MAX_MEMORY_SPACE);
}
public PrimeNumberChecker(int maxValue) {
if (MAX_MEMORY_SPACE < maxValue) {
maxValue = MAX_MEMORY_SPACE;
} else if (MIN_MEMORY_SPACE > maxValue) {
maxValue = MIN_MEMORY_SPACE;
}
this.primeNumberMarks = new boolean[maxValue+1];
markPrimeNumbers();
}
private void markPrimeNumbers() {
for (int i = 2; i < primeNumberMarks.length; ++i) {
primeNumberMarks[i] = true;
}
for (int i = 2; i*i <= primeNumberMarks.length; ++i) {
if (true == primeNumberMarks[i]) {
for (int j = i+i; j < primeNumberMarks.length; j += i) {
primeNumberMarks[j] = false;
}
}
}
return;
}
public boolean isPrime(int number) {
if (number < 0) {
return false;
} else if (number < primeNumberMarks.length) {
return primeNumberMarks[number];
} else {
return checkPrime(number);
}
}
private boolean checkPrime (int number) {
if (0 == (number%2) || 0 == (number%3)) {
return false;
}
int factor = 5;
while (factor*factor <= number) {
if (0 == number%factor) {
return false;
}
factor += 2;
if (0 == number%factor) {
return false;
}
factor += 4;
}
return true;
}
}