import java.util.*;
public class Main {
private static boolean isPrime(long n) {
if(n < 2)
return false;
for (long i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}
public static int findPrime(int q){
int counter = 0;
for(int i = 1; ; i++) {
if(isPrime(i))
counter++;
if(counter == q) {
return i;
}
}
}
public static void calculate(Stack<Integer> stack1,int q){
if(q==0){
return ;
}
Stack<Integer> stack2= new Stack<Integer>();
Stack<Integer> stack3 = new Stack<Integer>();
for(int i=0;i<q;i++){
if(stack1.isEmpty()){
break;
}
int prime=findPrime(q);
while(!stack1.isEmpty()){
int element=stack1.pop();
if(element%prime==0){
stack2.push(element);
}else{
stack3.push(element);
}
}
while(!stack2.empty())
{
System.out.println(stack2.peek());
stack2.pop();
}
stack1=stack3;
while(!stack3.empty())
stack3=new Stack<>();
}
while(!stack1.empty())
{
System.out.println(stack1.peek());
stack1.pop();
}
}
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
int N=sc.nextInt();
int Q=sc.nextInt();
int arr[]=new int[N];
Stack<Integer> stack=new Stack<Integer>();
for(int i=0;i<N;i++){
arr[i]=sc.nextInt();
stack.push(arr[i]);
}
calculate(stack,Q);
}
}
My two test cases are failing for this question.