-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path058-spiral-primes.js
More file actions
93 lines (76 loc) · 2.01 KB
/
058-spiral-primes.js
File metadata and controls
93 lines (76 loc) · 2.01 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
/**
* Spiral Primes
* Time Complexity: O(L * log^3 n)
* Space Complexity: O(1)
*/
function processData(input) {
const threshold = parseFloat(input.trim());
function modPow(base, exp, mod) {
let res = 1n;
base %= mod;
while (exp > 0n) {
if (exp & 1n) res = (res * base) % mod;
base = (base * base) % mod;
exp >>= 1n;
}
return res;
}
function isPrime(n) {
if (n < 2n) return false;
if (n === 2n || n === 3n) return true;
if (n % 2n === 0n) return false;
let d = n - 1n;
let s = 0n;
while ((d & 1n) === 0n) {
d >>= 1n;
s++;
}
const bases = [2n, 3n, 5n, 7n, 11n, 13n];
for (let a of bases) {
if (a >= n) continue;
let x = modPow(a, d, n);
if (x === 1n || x === n - 1n) continue;
let continueOuter = false;
for (let r = 1n; r < s; r++) {
x = (x * x) % n;
if (x === n - 1n) {
continueOuter = true;
break;
}
}
if (continueOuter) continue;
return false;
}
return true;
}
let side = 1n;
let primes = 0n;
let total = 1n;
while (true) {
side += 2n;
const s = side;
const step = side - 1n;
const c1 = s * s;
const c2 = c1 - step;
const c3 = c2 - step;
const c4 = c3 - step;
if (isPrime(c2)) primes++;
if (isPrime(c3)) primes++;
if (isPrime(c4)) primes++;
total += 4n;
const ratio = Number(primes * 100n) / Number(total);
if (ratio < threshold) {
console.log(side.toString());
return;
}
}
};
process.stdin.resume();
process.stdin.setEncoding("ascii");
let _input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});