Look for the GCD (greatest common divisor) of more than 2 integers?

Alain Tiemblo picture Alain Tiemblo · Dec 11, 2012 · Viewed 11.1k times · Source

I already have a function that finds the GCD of 2 numbers.

function getGCDBetween($a, $b)
{
    while ($b != 0)
    {
        $m = $a % $b;
        $a = $b;
        $b = $m;
    }
    return $a;
}

But now, I would like to extend this function to find the GCD of N points. Any suggestion ?

Answer

Adrien Gibrat picture Adrien Gibrat · Jul 6, 2013

There is a more elegant way to do this :

// Recursive function to compute gcd (euclidian method)
function gcd ($a, $b) {
    return $b ? gcd($b, $a % $b) : $a;
}
// Then reduce any list of integer
echo array_reduce(array(42, 56, 28), 'gcd'); // === 14

If you want to work with floating points, use approximation :

function fgcd ($a, $b) {
    return $b > .01 ? fgcd($b, fmod($a, $b)) : $a; // using fmod
}
echo array_reduce(array(2.468, 3.7, 6.1699), 'fgcd'); // ~= 1.232

You can use a closure in PHP 5.3 :

$gcd = function ($a, $b) use (&$gcd) { return $b ? $gcd($b, $a % $b) : $a; };