package org.brausch;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class SiebPanel extends JPanel {
	final static int ROOT = 1000;
	final static boolean NOPRIME[] = new boolean[ROOT*ROOT];

	public static void main(String[] args) {		
		long start = System.currentTimeMillis();
		int countPrims = ROOT*ROOT - 2; // 0 and 1 are no primes
		for (int i = 2; i < ROOT; i++) { // Therefore we start with 2
			if (NOPRIME[i]) {
				continue;
			}
			for (int x = i*2; x < ROOT*ROOT; x+=i) {
				if (!NOPRIME[x]) {
					NOPRIME[x] = true;
					countPrims--;
				}
			}
		}
		System.out.println("Time Elapsed: " + (System.currentTimeMillis() - start) + "ms");
		System.out.println("There are " + countPrims + " Prime numbers between 2 and " + ROOT*ROOT);
		openWindow("Sieb des Erathosthenes");
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		for (int i = 2; i < ROOT*ROOT; i++) {
			if (!NOPRIME[i]) {
				int x = i % ROOT;
				int y = i / ROOT;
				g.drawLine(x, y, x, y);						
			}
		}
	}
	
	private static void openWindow(String title) {
		JFrame frame = new JFrame(title);
		frame.getContentPane().add(new SiebPanel());
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		frame.setVisible(true);
		frame.setSize(ROOT, ROOT + frame.getHeight());
	}
}
