by Neal R. Wagner
Copyright © 2001 by Neal R. Wagner. All rights reserved.
NOTE: This site is obsolete. See book draft (in PDF):
// GCD: Greatest Common Divisor
public class GCD {
public static long gcd1(long x, long y) {
if (y == 0) return x;
return gcd1(y, x % y);
}
public static long gcd2(long x, long y) {
while (y != 0) {
long r = x % y;
x = y; y = r;
}
return x;
}
public static void main(String[] args) {
long x = Long.parseLong(args[0]);
long y = Long.parseLong(args[1]);
long z = GCD.gcd1(x, y);
System.out.println("Method 1: gcd(" + x + ", " + y + ") = " + z);
z = GCD.gcd2(x, y);
System.out.println("Method 2: gcd(" + x + ", " + y + ") = " + z);
}
}
Here are several runs of this program:
% java GCD 819 462 Method 1: gcd(819, 462) = 21 Method 2: gcd(819, 462) = 21 % java GCD 40902 24140 Method 1: gcd(40902, 24140) = 34 Method 2: gcd(40902, 24140) = 34