forked from prabaprakash/Hackerrank-JavaScript-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwaiter.js
80 lines (64 loc) · 1.65 KB
/
waiter.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});
process.stdin.on('end', _ => {
inputString = inputString.trim().split('\n').map(str => str.trim());
main();
});
function readLine() {
return inputString[currentLine++];
}
function sieve(n) {
let prime = Array(n + 1).fill(true);
for (var i = 2; i < Math.round(Math.sqrt(n)); i++) {
if (prime[i] !== false) {
for (var j = Math.pow(i, 2); j < n; j = j + i) {
prime[j] = false;
}
}
}
let p = [];
for (var j = 2; j < n; j++) {
if (prime[j] === true) p.push(j);
};
return p;
}
function waiter(number, qq, ws) {
let primenumbers = sieve(10000);
let a = number;
for (let q = 0; q < qq; q++) {
let c = [];
let d = []
while (a.length > 0) {
let val = a.pop();
if (val % primenumbers[q] !== 0) {
c.push(val);
}
else {
d.push(val);
}
}
while (d.length > 0) {
ws.write(d.pop() + "\n");
}
a = c;
}
while (a.length > 0) {
ws.write(a.pop() + "\n");
}
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const nq = readLine().split(' ');
const n = parseInt(nq[0], 10);
const q = parseInt(nq[1], 10);
const number = readLine().split(' ').map(numberTemp => parseInt(numberTemp, 10));
waiter(number, q, ws);
ws.end();
}