Skip to content

Commit 6240085

Browse files
committed
83차 2번번 문제풀이
1 parent b8078c1 commit 6240085

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

live8/test83/문제2/황장현.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
const input = require('fs')
2+
.readFileSync(process.platform === 'linux' ? '/dev/stdin' : './input.txt')
3+
.toString()
4+
.trim()
5+
.split('\n')
6+
.map((el) => el.split(' ').map(Number));
7+
8+
const LIMIT = 1299709;
9+
const isPrime = Array(LIMIT + 1).fill(true);
10+
isPrime[0] = isPrime[1] = false;
11+
const primes = [];
12+
13+
for (let i = 2; i <= LIMIT; i++) {
14+
if (isPrime[i]) {
15+
primes.push(i);
16+
for (let j = i * 2; j <= LIMIT; j += i) {
17+
isPrime[j] = false;
18+
}
19+
}
20+
}
21+
22+
function solution(input) {
23+
const T = input[0];
24+
const list = input.slice(1);
25+
const result = [];
26+
27+
for (let numb of list) {
28+
if (isPrime[numb]) {
29+
result.push(0);
30+
continue;
31+
}
32+
33+
let left = 0,
34+
right = primes.length - 1;
35+
while (left < right) {
36+
let mid = Math.floor((left + right) / 2);
37+
if (primes[mid] >= numb) right = mid;
38+
else left = mid + 1;
39+
}
40+
41+
let prevPrime = primes[left - 1];
42+
let nextPrime = primes[left];
43+
44+
result.push(nextPrime - prevPrime);
45+
}
46+
return result.join('\n');
47+
}
48+
49+
console.log(solution(input));

0 commit comments

Comments
 (0)