/**
 * listenp.java - 03/10/01 - 01/12/01 - 05/05/02 - 19/01/11 - 05/06/16 - 28/08/22
 *
 * liste les nombres premiers ŕ partir d'un nombre donné
 * Utilise la fonction BigInteger.nextProbablePrime()
 * qui retourne un nombre; la probabilité pour qu'il soit premier
 * est 1 - 2^(-100)
 *
 * Utilise le test de primalité de Miller-Rabin (?)
 */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.math.BigInteger;

public class listenp extends JPanel implements ActionListener {
	static final long serialVersionUID = 220828L;
	JTextField tn1 = new JTextField ("2", 10);
	JTextField tn2 = new JTextField ("100", 10);
	BigInteger n1, n2, deux, trois;
	TextArea ta = new TextArea ("", 0, 0, TextArea.SCROLLBARS_VERTICAL_ONLY);
	JButton ok = new JButton ("Ok");
	JButton efface = new JButton ("Efface");
	String message;

	public listenp() {
		setFont (new Font ("Arial", Font.PLAIN, 12));
		setLayout (new BorderLayout());
		JPanel pnl = new JPanel();
		pnl.setBackground (Color.lightGray);
		add (pnl, BorderLayout.NORTH);
		pnl.add (new JLabel ("Nombres premiers de : "));
		pnl.add (tn1);
		pnl.add (new JLabel ("ŕ : "));
		pnl.add (tn2);
		pnl.add (ok);
		ok.addActionListener (this);
		pnl.add (efface);
		efface.addActionListener (this);
		add (ta, BorderLayout.CENTER);
		deux = BigInteger.valueOf (2);
		trois = BigInteger.valueOf (3);
	}

	private BigInteger capte (JTextField tf, BigInteger bi) {
		try {
			bi = new BigInteger (tf.getText());
		}
		catch (NumberFormatException nfe) {}
		if (bi.compareTo (BigInteger.ZERO) <= 0)
			bi = BigInteger.ONE;
		tf.setText (bi.toString());
		return bi;
	}

	public void actionPerformed (ActionEvent evt) {
		if (evt.getSource() == ok) {
			n1 = capte(tn1, n1).subtract (BigInteger.ONE);
			n2 = capte (tn2, n2);
// liste des nombres premiers impairs de n1 ŕ n2
			ta.setText ("");
			while (n1.compareTo (n2) <= 0) {
				n1 = n1.nextProbablePrime();
				ta.append (n1 + " ");
			}
		} else if (evt.getSource() == efface) {
			ta.setText ("");
		}
	}

	public static void main (String [] args) {
		int w = 600;
		int h = 300;

		listenp a = new listenp();

		JFrame f = new JFrame ("Liste de nombres premiers");
		f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
		f.add (a);
		f.setSize (w, h);
		f.setVisible (true);
	}

}
