import java.awt.*; import java.applet.*; /** Program: NaivePrimalityTester Purpose: most naive primality tester @author: Paul Garrett, garrett@math.umn.edu copyright Paul Garrett, GNU Public License, 1997 @version: Sat Oct 18 18:06:12 CDT 1997 */ public class NaivePrimalityTester extends Applet { int height, width; Color background_color, foreground_color; TextField firstTF; // to enter the number TextArea TA; // to display the computation Button computeB; // also to compute... long theX; // the number whose primality is being tested boolean queryOK; // boolean which tells whether data is ok // to try to execute algorithm upon String ErrorMessage; /*********************/ public void init() { try { background_color = new Color(Integer.parseInt(getParameter("background_color"), 16)); foreground_color = new Color(Integer.parseInt(getParameter("foreground_color"), 16)); height = Integer.parseInt(getParameter("height")); width = Integer.parseInt(getParameter("width")); } catch (Exception e) { background_color = new Color(0xbaaaaa); foreground_color = new Color(0x503030); height = 320; width = 550; } setBackground(background_color); setForeground(foreground_color); setFont(new Font("TimesRoman", Font.PLAIN, 14)); ErrorMessage = new String("Inputs are not integers, or"); ErrorMessage += " are too large for the implementation"; theX = 1234432112347L; add(new Label("Enter the integer ")); firstTF = new TextField(""+theX, 24); add(firstTF); computeB = new Button("compute"); add(computeB); TA = new TextArea(2,40); add(TA); queryOK = true; // not OK yet to try to compute compute(theX); } final synchronized void compute(long x) { boolean queryPrimeSoFar = true; TA.setText(" \n"); if (x % 2 == 0) { TA.setText(" 2 divides "+x); queryPrimeSoFar = false; } int i = 3; while (i<=Math.sqrt(Math.abs(x)) && queryPrimeSoFar) { if (x % i == 0) { TA.setText(" "+i+" divides "+x); queryPrimeSoFar = false; } i += 2; // in any case } if (queryPrimeSoFar && x > 1) { TA.setText(" "+x+" is prime "); } } public final synchronized boolean action(Event e, Object arg) { if (e.target instanceof TextField || e.target == computeB) { String first = Clean.clean(firstTF.getText()); if (first.length() <= 18) { theX = Long.parseLong(first); queryOK = true; } else { queryOK = false; } if (queryOK) { compute(theX); } else { TA.setText(ErrorMessage); } return true; } else { return false; // old AWT event model... } } } // the end /******************************* * * The End * *******************************/