import java.io.*; class BB { static int size = 10; private int buf[]; private int next_full = 0; private int next_free = 0; private int full_slots = 0; public BB() { buf = new int[size]; } synchronized void insert(int n) { while (full_slots == size) { try { wait(); } catch(InterruptedException e) { } } buf[next_free] = n; ++full_slots; next_free = (next_free + 1) % size; notify(); } synchronized int remove() { while (full_slots == 0) { try { wait(); } catch(InterruptedException e) { } } int rtn = buf[next_full]; --full_slots; next_full = (next_full + 1) % size; notify(); return rtn; } } class Eratosthenes extends Thread { private int p; // my prime BB in_q; BB out_q; public Eratosthenes(BB input_queue) { in_q = input_queue; } public void run() { p = in_q.remove(); System.out.println(p); int i; while ((i = in_q.remove()) != 0) { if (i % p != 0) { if (out_q == null) { out_q = new BB(); (new Eratosthenes(out_q)).start(); } out_q.insert(i); } } if (out_q != null) { out_q.insert(0); } } } public class Sieve { public static void main(String args[]) throws IOException { int limit = (new Integer(args[0])).intValue(); BB first_buf = new BB(); (new Eratosthenes(first_buf)).start(); for (int i = 2; i <= limit; i++) { first_buf.insert(i); } first_buf.insert(0); } }