import java.beans.*; import java.io.*; import javax.swing.JLabel; /** * Example application for factoring small numbers. * * @author Philip Milne */ public class Factorize { private JLabel output; private Factorizer factorizer; private class Factorizer implements Runnable { private long n; private boolean abort; public Factorizer(long n) { this.n = n; } public void run() { output.setText("thinking ..."); String factors = ""; int i = 2; int sn = (int)Math.sqrt(n); // Factorization by trial division while(i < sn) { if (abort) { output.setText("= "); return; } if (n % i == 0) { factors = factors + i + " * "; n = n / i; sn = (int)Math.sqrt(n); } else { i = i + 1; } } output.setText("= " + factors + n); } } public void setOutput(JLabel output) { this.output = output; } public void loading() { System.out.println("Loading user interface..."); } public void calculate(String input) { try { stop(); factorizer = new Factorizer(Long.parseLong(input)); Thread thread = new Thread(factorizer); thread.setPriority(Thread.MIN_PRIORITY); thread.start(); } catch(NumberFormatException e) { output.setText("Field must be a number"); } } public void stop() { if (factorizer != null) { factorizer.abort = true; } } public Factorize() {} public Factorize(String archiveName) { try { XMLDecoder d = new XMLDecoder( new BufferedInputStream( new FileInputStream(archiveName)), this); d.readObject(); d.close(); } catch(FileNotFoundException e) { System.err.println(e); System.exit(0); } } public static void main(String[] args) { new Factorize("Factorize.xml"); } }