import java.awt.*; import java.applet.*; /** Program: Euclidean Algorithm Purpose: computes gcd of two smallish integers by Euclidean Algorithm @author: Paul Garrett, garrett@math.umn.edu copyright Paul Garrett, GNU Public License, 2000 @version: 18 July 2000 */ final public class Euclid extends Applet { int height, width; Color background_color, foreground_color; TextField firstTF, secondTF; // to enter the two numbers TextArea TA; // to display the computation Button computeB; // to do computation, also long theX, theY; long origX, origY; // the two numbers whose GCD is being computed 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, 12)); ErrorMessage = new String("Inputs are too large for the implementation"); origX = theX = 7654321; origY = theY = 56789; add(new Label("First ")); firstTF = new TextField(""+theX, 18); add(firstTF); add(new Label(" Second ")); secondTF = new TextField(""+theY, 18); add(secondTF); computeB = new Button("compute"); add(computeB); TA = new TextArea(35,60); TA.resize(500,500); add(TA); queryOK = true; // not OK yet to try to compute recursiveComputation(); } final synchronized void recursiveComputation() { TA.setText(""); long q,r; r = theX % Math.abs(theY); // ((x % Math.abs(y)) + Math.abs(y)) % Math.abs(y); q = theX/Math.abs(theY); // ((x-r)/y; TA.appendText(" "+theX+" - ("+q+") * ("+theY+") = "+r); theX = theY; theY = r; while (r != 0) { r = theX % Math.abs(theY); // ((x % Math.abs(theY)) + Math.abs(y)) % Math.abs(y); q = theX/Math.abs(theY); // ((x-r)/y; TA.appendText("\n "+theX+" - ("+q+") * ("+theY+") = "+r); theX = theY; theY = r; } TA.appendText("\n\n So gcd of "); TA.appendText(origX+" and "+origY); TA.appendText(" is "+theX); } public final synchronized boolean action(Event e, Object arg) { if (e.target instanceof TextField || e.target == computeB) { String first = Clean.clean(firstTF.getText()); String second = Clean.clean(secondTF.getText()); if (first.length() <= 18 && second.length() <= 18) { origX = theX = Long.parseLong(first); origY = theY = Long.parseLong(second); queryOK = true; } else { queryOK = false; } if (queryOK) { recursiveComputation(); } else { TA.setText(ErrorMessage); } return true; } else { return false; // old AWT event model... } } } // the end of class EuclideanAlgorithm