-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path133-repunit-non-factors.js
More file actions
114 lines (93 loc) · 2.21 KB
/
133-repunit-non-factors.js
File metadata and controls
114 lines (93 loc) · 2.21 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**
* Repunit Non-Factors
* Time Complexity: O(L_max + T * log T)
* Space Complexity: O(L_max)
*/
const fs = require("fs");
function processData() {
const buffer = fs.readFileSync(0);
let bufferIdx = 0;
function readString() {
let start = bufferIdx;
while (bufferIdx < buffer.length && buffer[bufferIdx] <= 32) {
bufferIdx++;
}
if (bufferIdx >= buffer.length) return null;
start = bufferIdx;
while (bufferIdx < buffer.length && buffer[bufferIdx] > 32) {
bufferIdx++;
}
return buffer.toString("utf8", start, bufferIdx);
}
function readInt() {
const s = readString();
return s ? parseInt(s, 10) : null;
}
const T = readInt();
if (T === null) return;
const queries = new Array(T);
let maxL = 0;
for (let i = 0; i < T; i++) {
const l = readInt();
queries[i] = { L: l, index: i, ans: 0 };
if (l > maxL) maxL = l;
}
queries.sort((a, b) => a.L - b.L);
const sieve = new Uint8Array(maxL + 1);
const limitSq = Math.floor(Math.sqrt(maxL));
sieve[0] = 1;
sieve[1] = 1;
for (let i = 2; i <= limitSq; i++) {
if (sieve[i] === 0) {
for (let j = i * i; j <= maxL; j += i) {
sieve[j] = 1;
}
}
}
function modPow(base, exp, mod) {
let res = 1;
let b = base;
let e = exp;
while (e > 0) {
if ((e & 1) === 1) res = (res * b) % mod;
b = (b * b) % mod;
e >>= 1;
}
return res;
}
let currentSum = 0;
let qIdx = 0;
for (let p = 2; p <= maxL; p++) {
while (qIdx < T && queries[qIdx].L <= p) {
queries[qIdx].ans = currentSum;
qIdx++;
}
if (sieve[p] === 0) {
let isFactor = false;
if (p === 2 || p === 3 || p === 5) {
isFactor = false;
} else {
const E = modPow(10, 30, p - 1);
const check = modPow(10, E, p);
if (check === 1) {
isFactor = true;
}
}
if (!isFactor) {
currentSum += p;
}
}
}
while (qIdx < T) {
queries[qIdx].ans = currentSum;
qIdx++;
}
const results = new Array(T);
for (let i = 0; i < T; i++) {
results[queries[i].index] = queries[i].ans;
}
console.log(results.join("\n"));
};
if (require.main === module) {
processData();
};