直接上代码
//greatest common divisor
public class GCD {
// 辗转相除法
public int getGcd1(int x, int y) {
return (y == 0) ? x : getGcd1(y, x % y);
}
public int getGcd2(int x, int y) {
if (x < y)
return getGcd2(y, x);
if (y == 0)
return x;
return getGcd2(x - y, y);
}
public int getGcd3(int x, int y) {
if (x < y)
return getGcd3(y, x);
if (y == 0)
return x;
if ((x & 1) == 0) {
if ((y & 1) == 0) {// x偶数 y偶数
return getGcd3(x >> 1, y >> 1) << 1;
} else {// x偶数 y奇数
return getGcd3(x >> 1, y);
}
} else {
if ((y & 1) == 0) { // x奇数 y偶数
return getGcd3(x, y >> 1);
} else { // x奇数 y奇数
return getGcd3(x - y, y);
}
}
}
public static void main(String[] args) {
System.out.println(new GCD().getGcd1(2, 8));
System.out.println(new GCD().getGcd2(12, 8));
System.out.println(new GCD().getGcd2(66, 999));
}
}