/************************************************************ *Program to find the greatest common divisor of two integers * *Algorithm by Euclid * *Jay Henniger *June 26, 2001 *henniger@cam.cornell.edu ************************************************************/ public class GCD{ public static void main(String[] args){ //Declare variables int divisor, dividend, remainder, previousRemainder; int largerNumber, smallerNumber, gcd; //Print out instructions and input the two numbers System.out.println("\nThis program will compute the " + "greatest common divisor of two integers.\n"); System.out.println("Please enter the first integer:"); largerNumber = SavitchIn.readLineInt(); System.out.println("\nPlease enter the second integer:"); int temp = SavitchIn.readLineInt(); //Assign larger input to largerNumber, smaller to smallerNumber if (temp <= largerNumber) { smallerNumber = temp; } else { smallerNumber = largerNumber; largerNumber = temp; } //initialize dividend and divisor for algorithm dividend = largerNumber; divisor = smallerNumber; //Set remainder to something to make sure we get into the while loop. //Specifically, set remainder to be equal to smallerNumber so that the //output of the algorithm will be correct even if smallerNumber divides //largerNumber exactly. remainder = smallerNumber; previousRemainder = -9999; //junk value to keep compiler happy //Algorithm to calculate GCD of largerNumber and smallerNumber while (remainder != 0) { previousRemainder = remainder; remainder = dividend % divisor; dividend = divisor; divisor = remainder; } gcd = previousRemainder; //Print out the two numbers and their GCD System.out.println("\nThe GCD of " + smallerNumber + " and " + largerNumber + " is " + gcd + "."); } }