n! = n * (n - 1) * … * 2 * 1
|
JS |
.NET |
// <applet code="FactApp.class" width="300" height="240"></applet> /** * 階乗を求める Java Applet * @see https://mind.kittttttan.info/java/factapp.html */ import java.applet.Applet; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JTextArea; import javax.swing.JScrollPane; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.math.BigInteger; public class FactApp extends Applet implements ActionListener { /** * default serialVersionUID */ private static final long serialVersionUID = 1L; private static final int MAX = 99999; private JPanel panel1; private JPanel panel2; private JButton btn; private JTextArea ta; private JScrollPane sp; private JLabel labelt; private JTextField tf; /** * Initialize */ public void init() { btn = new JButton("OK"); btn.addActionListener(this); tf = new JTextField("777", 7); labelt = new JLabel("Time[ms]"); ta = new JTextArea(10, 20); ta.setLineWrap(true); sp = new JScrollPane(ta); panel1 = new JPanel(); panel1.add(tf); panel1.add(btn); panel1.add(labelt); panel2 = new JPanel(); panel2.add(sp); add(panel1, BorderLayout.CENTER); add(panel2, BorderLayout.SOUTH); } @Override public void actionPerformed(ActionEvent arg0) { int n; try { n = Integer.parseInt(tf.getText()); } catch (NumberFormatException err) { ta.setText("Input Number 1, 2, ..."); labelt.setText("Error"); return; } if (n > MAX) { ta.setText("too BIG"); labelt.setText("Error"); return; } long start = System.currentTimeMillis(); BigInteger p = fact(n); long stop = System.currentTimeMillis(); ta.setText(p.toString()); labelt.setText(String.valueOf(stop - start) + "ms"); } public static BigInteger fact(int n) { BigInteger b = BigInteger.ONE; for (int i = 2; i < n + 1; i++) { b = b.multiply(BigInteger.valueOf(i)); } return b; } }