Talk:Java Training Course/JT05
Jump to navigation
Jump to search
Program
public class GreatestCommonDivisor {
/** Computes the greatest common divisor (GCD) of 2 integers
* @param a first integer
* @param b second integer
* @return gcd(a,b)
*/
public static int gcd(int a, int b) {
int result = Math.abs(a);
if (result != 1) {
int p = result;
int q = Math.abs(b);
while (q != 0) {
int temp = q;
q = p % q;
p = temp;
}
result = p;
} // if > 1
return Math.abs(result);
} // gcd(a, b)
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println("gcd(" + a + "," + b + ") = " + gcd(a, b));
} // main
} // GreatestCommonDivisor
Test Results
./JTC$ javac GreatestCommonDivisor.java ./JTC$ java GreatestCommonDivisor 0 0 gcd(0,0) = 0 ./JTC$ java GreatestCommonDivisor 0 1 gcd(0,1) = 1 ./JTC$ java GreatestCommonDivisor 1 0 gcd(1,0) = 1 ./JTC$ java GreatestCommonDivisor 1 1 gcd(1,1) = 1 ./JTC$ java GreatestCommonDivisor 4 4 gcd(4,4) = 4 ./JTC$ java GreatestCommonDivisor 12 8 gcd(12,8) = 4 ./JTC$ java GreatestCommonDivisor 3 5 gcd(3,5) = 1 ./JTC$ java GreatestCommonDivisor 81 24 gcd(81,24) = 3 ./JTC$ java GreatestCommonDivisor 4096 256 gcd(4096,256) = 256