Skip to content

Instantly share code, notes, and snippets.

@aurmil
Created July 28, 2018 09:32
Show Gist options
  • Save aurmil/1158e097205cf62044b87766512e8fad to your computer and use it in GitHub Desktop.
Save aurmil/1158e097205cf62044b87766512e8fad to your computer and use it in GitHub Desktop.
PHP : GCD
<?php
/**
* Calculate Greatest Common Divisor of 2 integers.
* The result is always positive even if either of, or both, input operands are negative.
*
* @param int $a
* @param int $b
* @return int
*/
function gcd($a, $b)
{
$a = abs((int) $a);
$b = abs((int) $b);
if ((0 == $a) || (0 == $b)) {
$gcd = 1;
} elseif ($a == $b) {
$gcd = $a;
} else {
if ($a < $b) {
$rest = $a;
$a = $b;
$b = $rest;
}
do {
$rest = $a % $b;
$a = $b;
$b = $rest;
} while (0 !== $rest);
$gcd = $a;
}
return $gcd;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment