-
Notifications
You must be signed in to change notification settings - Fork 0
/
twins29(1).java
57 lines (47 loc) · 1.25 KB
/
twins29(1).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.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
class twin {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
System.out.println(solve(n, m));
sc.close();
}
static int solve(int n, int m) {
int size = m - n + 1;
List<Integer> primeDivisors = sievePrimes(size);
boolean[] primes = new boolean[size];
Arrays.fill(primes, true);
for (int primeDivisor : primeDivisors) {
for (int i = n / primeDivisor * primeDivisor; i <= m; i += primeDivisor) {
if (i >= n && i > primeDivisor) {
primes[i - n] = false;
}
}
}
int result = 0;
for (int i = 0; i + 2 < primes.length; i++) {
if (n + i >= 2 && primes[i] && primes[i + 2]) {
result++;
}
}
return result;
}
static List<Integer> sievePrimes(int limit) {
boolean[] primes = new boolean[limit + 1];
Arrays.fill(primes, true);
List<Integer> result = new ArrayList<Integer>();
for (int i = 2; i < primes.length; i++) {
if (primes[i]) {
result.add(i);
for (long j = (long) i * i; j < primes.length; j += i) {
primes[(int) j] = false;
}
}
}
return result;
}
}