Skip to content

Instantly share code, notes, and snippets.

@iluxonchik
Created April 23, 2014 20:14
Show Gist options
  • Save iluxonchik/11230686 to your computer and use it in GitHub Desktop.
Save iluxonchik/11230686 to your computer and use it in GitHub Desktop.
Binary GCD algorithm php implementation. Iterative version.
function binary_gcd($a, $b){
/* computes and returns the greatest common divisor between a and b */
/*
* Binary GCD Algorithm, according to Wikipedia "binary GCD can be about 60%
* more efficient (in terms of the number of bit operations) on average than the Euclidean algorithm".
* More about the Binary GCD Algorithm: http://en.wikipedia.org/wiki/Binary_GCD_algorithm
* Java Implementation: http://introcs.cs.princeton.edu/java/23recursion/BinaryGCD.java.html
* C++ Implementation: https://gist.github.com/cslarsen/1635213
*/
$shiftleft = 0;
while( ($a && $b) && ($a != $b) ){
$a_is_even = !($a & 1); // check if a is even
$b_is_even = !($b & 1); // check if b is even
// if both a and b are even
if ($a_is_even && $b_is_even){
$shiftleft++;
$a >>= 1; // shift a right by 1 bit (i.e. divide by 2)
$b >>= 1; // shift b right by 1 bit (i.e. divide by 2)
}
// if a is even and b is odd
else if ($a_is_even && !$b_is_even)
$a >>= 1;
// if b is even and a is odd
else if (!$a_is_even && $b_is_even)
$b >>= 1;
// if both a and b are odd and a >= b
else if ($a >= $b)
$a = ($a-$b) >> 1;
// if both a and b are odd and a < b
else{
$temp = $a;
$a = ($b - $a) >> 1;
$b = $temp;
}
}
// if $a is 0, then shift $b left by $shiftleft bits, otherwise, shit $a by $shiftleft bits
return !$a ? $b << $shiftleft : $a << $shiftleft;
/*
* NOTE: Doing (inetger & 1) check if it's even.
* Example: 1 --> 0001
* 6 --> 0110
* 0001 & 0110 ---> 0000 (which is 0)
*
* 1 --> 0001
* 7 --> 0111
* 0001 & 0111 ---> 0001 (which is 1)
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment