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);
}