-
Notifications
You must be signed in to change notification settings - Fork 0
/
countSemiprimes.js
66 lines (53 loc) · 1.54 KB
/
countSemiprimes.js
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
// -----------------------------------------------------------------------------
// COUNT SEMIPRIMES
// Count the semiprime numbers in the given range [a..b]
//
// Report: https://app.codility.com/demo/results/training9WQUJ4-PFW/
// -----------------------------------------------------------------------------
function solution(N, P, Q) {
function get_factorization_array(n) {
let f = Array(n+1).fill(0)
let i = 2
while (i * i <= n) {
if (f[i] == 0) {
k = i * i
while (k <= n) {
if (f[k] == 0) {
f[k] = i
}
k += i
}
}
i += 1
}
return f
}
function is_semiprime(x, f) {
let count = 0;
while (f[x] > 0) {
count +=1
x /= f[x]
if (count > 1) {
return false
}
}
return count == 1
}
let f_array = get_factorization_array(N)
let M = P.length
let prefix_sums = Array(N+1).fill(0)
for (let i=4; i < N+1; ++i) {
if (is_semiprime(i, f_array)) {
prefix_sums[i] = prefix_sums[i-1] + 1;
} else {
prefix_sums[i] = prefix_sums[i-1]
}
}
// console.log(prefix_sums)
let answer = Array(M).fill(0)
for (let i = 0; i < M; i++) {
answer[i] = prefix_sums[Q[i]] - prefix_sums[P[i]-1]
}
return answer
}
console.log(solution(26, [1, 4, 16], [26, 10, 20])) // [10, 4, 0]