I know that Euclid’s algorithm is the best algorithm for getting the GCD (great common divisor) of a list of positive integers. But in practice you can code this algorithm in various ways. (In my case, I decided to use Java, but C/C++ may be another option).
I need to use the most efficient code possible in my program.
In recursive mode, you can write:
static long gcd (long a, long b){
a = Math.abs(a); b = Math.abs(b);
return (b==0) ? a : gcd(b, a%b);
}
And in iterative mode, it looks like this:
static long gcd (long a, long b) {
long r, i;
while(b!=0){
r = a % b;
a = b;
b = r;
}
return a;
}
There is also the Binary algorithm for the GCD, which may be coded simply like this:
int gcd (int a, int b)
{
while(b) b ^= a ^= b ^= a %= b;
return a;
}