-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularPrimes.java
More file actions
56 lines (41 loc) · 1.02 KB
/
CircularPrimes.java
File metadata and controls
56 lines (41 loc) · 1.02 KB
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
package devjava;
public class CircularPrimes {
public static boolean[] listPrimality(int n) {
if (n < 0) {
throw new IllegalArgumentException("Negative size");
}
boolean[] prime = new boolean[n + 1];
if (n >= 2) {
prime[2] = true;
}
for (int i = 3; i <= n; i += 2) {
prime[i] = true;
}
for (int i = 3, end = (int) Math.sqrt(n); i <= end; i += 2) {
if (prime[i]) {
for (int j = i * i; j <= n; j += i << 1) {
prime[j] = false;
}
}
}
return prime;
}
private static final int LIMIT = (int) Math.pow(10, 6);
private static boolean[] isPrime = listPrimality(LIMIT - 1);
private static boolean isCircularPrime(int n) {
String s = Integer.toString(n);
for (int i = 0; i < s.length(); i++) {
if (!isPrime[Integer.parseInt(s.substring(i) + s.substring(0, i))])
return false;
}
return true;
}
public static void main(String[] args) {
int count = 0;
for (int i = 0; i < isPrime.length; i++) {
if (isCircularPrime(i))
count++;
}
System.out.println(count);
}
}