33-1(二进制的gcd算法) 与计算余数的执行速度相比,大多数计算机执行减法运算,测试一个二进制整数的奇偶性运算以及折半运算的执行速度都要更快些。本题所讨论的二进制gcd算法中避免了欧几里得算法中对余数的计算过程。
a.证明:如果a和b都是偶数,则gcd(a,b)=2gcd(a/2,b/2).
b.证明:如果a是奇数,b是偶数,则gcd(a,b)=gcd(a,b/2).
c.证明:如果a和b都是奇数,则gcd(a,b)=gcd((a-b)/2,b).
d.设计一个有效的二进制算法,输入整数为a和b(a≥b),并且算法的运行时间为O(lg a).假定每个减法运算,测试奇偶性运算以及折半运算都能在单位时间行。
/*
if a and b are both even, then gcd(a,b)= 2 * gcd(a/2,b/2).
if a is odd and b is even, then gcd(a,b) = gcd(a,b/2).
that if a and b are both odd, then gcd(a,b) = gcd((a-b)/2,b).
Design an efficient binary gcd algorithm for input integers a and b, where
a >= b, that runs in O(lg a) time.
*/
public static int binaryGcd(int a, int b) {// assume a>=b;
a = Math.abs(a); // gcd(a,b) = gcd(|a|,|b|) 31.8
b = Math.abs(b);
if (a < b) {
return binaryGcd(b, a);
}
if (b == 0) {
return a;
}
if ((a & 1) == 0 && (b & 1) == 0) {// both a and b are even
int half = binaryGcd(a >> 1, b >> 1);
return half << 1;
}
else if ((a & 1) == 1 && (b & 1) == 0) {// a odd, b even
return binaryGcd(a, b >> 1);
}
else if ((a & 1) == 0 && (b & 1) == 1) {// a even, b odd
return binaryGcd(a >> 1, b);
}
else { // a odd, b odd
return binaryGcd((a - b) >> 1, b);
}
}
public static void main(String[] args) {
int gcd = binaryGcd(-21, 15);
System.out.println("gcd(-21,15)="+gcd);
int a = 2*3*7*13*5;
int b = 17*3*14*2*5;
gcd = binaryGcd(a,b);
System.out.println("gcd(a,b)="+gcd);
}