Created
July 28, 2018 09:32
-
-
Save aurmil/1158e097205cf62044b87766512e8fad to your computer and use it in GitHub Desktop.
PHP : GCD
This file contains hidden or 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
<?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