/**
 * suite_syracuse_bi.java - 02/01/10
 * 
 * @author Jean-Paul QUELEN
 * 
 * suite de syracuse - utilisation des BigInteger
 * ajout de main() le 08/01/18 - modification le 29/08/22
 */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.math.BigInteger;

public class suite_syracuse_bi extends JFrame implements ActionListener {
	static final long serialVersionUID = 220829L;
	JTextField tn;
	TextArea ta;
	JButton ok;
	BigInteger deux = new BigInteger ("2");
	BigInteger trois = new BigInteger ("3");

	public suite_syracuse_bi (String titre) {
		super (titre);
		setFont (new Font ("Arial, Helvetica, sans-serif", Font.PLAIN, 10));
		setBackground (Color.lightGray);
		setLayout (new BorderLayout());
		JPanel p = new JPanel();
		add (p, BorderLayout.NORTH);
// installe N = 1 et le bouton Ok dans le panneau "nord"
		p.add (new JLabel ("N ="));
		p.add (tn = new JTextField ("4", 10));
		p.add (ok = new JButton ("Ok"));
		ok.addActionListener (this);
// installe le champ de texte "ta" qui recevra les éléments de la suite dans le panneau central
		p = new JPanel();
		add (p);
		p.add (ta = new TextArea ("", 10, 40, TextArea.SCROLLBARS_VERTICAL_ONLY), BorderLayout.CENTER);
	}

// Traitement de l'appui sur le bouton "Ok"
	public void actionPerformed (ActionEvent evt) {
		if (evt.getSource() == ok ) {
			try {
				BigInteger n = new BigInteger (tn.getText());
				if (n.compareTo (BigInteger.ONE) >= 0) {						// if n >= 1
					ta.setText (n.toString() + " ");
// nombre entier valide => calcul des termes de la suite
					while (n . compareTo (BigInteger.ONE) > 0) {				// tant que n > 1
						if (n . mod (deux) . compareTo (BigInteger.ZERO) == 0)	// if n % 2 == 0
							n = n.divide (deux);								// n = n / 2
						else
							n = n.multiply(trois).add(BigInteger.ONE);			// n = n * 3 + 1
						ta.append (n.toString() + " ");
					}
//
				} else
					ta.setText ("Entrer un nombre entier > 0");
			}
			catch (NumberFormatException nfe) {
				ta.setText ("Entrer un nombre entier > 0");
			}
		}
	}

	public static void main (String [] args) {
		int w = 400;
		int h = 300;
		suite_syracuse_bi f = new suite_syracuse_bi ("suite_syracuse_bi");
		f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
		f.setSize (w, h);
		f.setVisible (true);
	}
}
