-
Notifications
You must be signed in to change notification settings - Fork 152
/
CountSemiprimes.java
72 lines (63 loc) · 2.52 KB
/
CountSemiprimes.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
package CountSemiprimes;
import java.util.*;
class Solution {
public int[] solution(int N, int[] P, int[] Q) {
// main idea:
// using "sieve of Eratosthenes"
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
boolean[] primeArray = new boolean[N+1]; // note: plus one for "0"
// initial settting (sieve of Eratosthenes)
Arrays.fill(primeArray, true); // initial setting: all primes
primeArray[0] = false; // not prime
primeArray[1] = false; // not prime
int sqrtN = (int)Math.sqrt(N);
// sieve of Eratosthenes
for(int i =1; i < sqrtN; i++){
if(primeArray[i] == true) // prime
{
int j = i + i;
for(j=j; j<=N; j=j+i){
primeArray[j] = false; // not prime
}
}
}
// store all primes in "List"
List<Integer> primeList = new ArrayList<>();
for(int i=2; i<= N; i++){
if(primeArray[i] == true){
primeList.add(i); // "i" is prime
}
}
// find "semiprimes"
boolean[] semiprimeArray = new boolean[N+1]; // note: plus one for "0"
Arrays.fill(semiprimeArray, false); // initial setting: all "not" semiprimes
long semiprimeTemp; // using "long" (be careful)
// for "primeList.size()"
for(int i=0; i< primeList.size(); i++){
for(int j=i; j< primeList.size(); j++){
semiprimeTemp = (long) primeList.get(i) * (long) primeList.get(j); // semiprimes
if(semiprimeTemp > N){
break;
}
else{
semiprimeArray[(int)semiprimeTemp] = true; // semiprimes
}
}
}
// compute "cumulative Count of semiprimes"
int[] semiprimeCumulateCount = new int [N+1]; // note: plus one for "0"
for(int i=1; i<=N; i++){
semiprimeCumulateCount[i] = semiprimeCumulateCount[i-1]; // cumulative
if(semiprimeArray[i] == true){
semiprimeCumulateCount[i]++; // semiprimes
}
}
// compute "results" (for each query)
int numQuery = Q.length;
int[] result = new int[numQuery];
for(int i=0; i< numQuery; i++){
result[i] = semiprimeCumulateCount[Q[i]] - semiprimeCumulateCount[P[i]-1]; // note: "P[i]-1" (not included)
}
return result;
}
}