forked from alexprut/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
60 lines (52 loc) · 1.34 KB
/
Solution.java
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
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.math.*;
public class Solution {
public static ArrayList<Integer> findNPrimes(int n) {
ArrayList<Integer> primes = new ArrayList<Integer>();
int i = 2;
while (primes.size() < n) {
BigInteger tmp = new BigInteger("" + i);
if (tmp.isProbablePrime(1000)) {
primes.add(i);
}
i++;
}
return primes;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int q = in.nextInt();
Stack<Integer> A = new Stack<Integer>();
ArrayList<Integer> primes = findNPrimes(q);
for (int i = 0; i < n; i++) {
A.push(in.nextInt());
}
ArrayList<Stack<Integer>> B = new ArrayList<Stack<Integer>>();
for (int i = 0; i < q; i++) {
Stack<Integer> tmpA = new Stack<Integer>();
Stack<Integer> BI = new Stack<Integer>();
while (!A.empty()) {
if (A.peek() % primes.get(i) == 0) {
BI.push(A.pop());
} else {
tmpA.push(A.pop());
}
}
B.add(BI);
A = tmpA;
}
for (int i = 0; i < q; i++) {
while (!B.get(i).empty()) {
System.out.println(B.get(i).pop());
}
}
while (!A.empty()) {
System.out.println(A.pop());
}
}
}