题目原文:
In Section 1.2.3, westudied Euclid’s algorithm for computing the greatest commondivisor(gcd) of two positive integers: the largest integer which divides them both. Here we will look at an alternative algorithm based on divide-and-conquer.
(a) Show that the following rule is true.
gcd(a,b) = 2gcd(a/2,b/2) if a,b are even
gcd(a,b) = gcd(a,b/2) if a is odd, b is even
gcd(a,b) = gcd((a−b)/2,b) if a,b are odd
(b) Give an efficient divide-and-conquer algorithm for greatest common divisor.
C++代码实现如下:
int gcd(int a, int b)
{
if (a == b)
return a;
if (a % 2 == 0 && b % 2 == 0)
return 2*gcd(a / 2, b / 2);
if (a % 2 == 0 && b % 2 != 0)
return gcd(a / 2, b);
if (a % 2 != 0 && b % 2 == 0)
return gcd(a, b / 2);
if (a % 2 != 0 && b % 2 != 0)
return gcd((a - b) / 2, b);
}