The easiest way perhaps is to use Euclidean algorithm but that is just too slow. So, the following is a bit faster algorithm called binary GCD:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int binaryGCD(int a, int b) { | |
if (a==b) | |
return a; | |
if (a==0) | |
return b; | |
if (b==0) | |
return a; | |
// divide a and b by 2 until they become both odd numbers | |
int p2a, p2b; | |
p2a = p2b = 0; | |
while ((a&1) == 0) { | |
p2a++; | |
a >>= 1; | |
} | |
while ((b&1) == 0) { | |
p2b++; | |
b >>= 1; | |
} | |
int minpower = p2a < p2b ? p2a : p2b; | |
if (a>b) | |
return binaryGCD((a-b)>>1, b) << minpower; | |
else | |
return binaryGCD((b-a)>>1, a) << minpower; | |
} |
The code above is my variant of binary gcd found in here. It is a bit harder to read but perhaps a bit faster though.
No comments:
Post a Comment