Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 341
Alain Tiemblo Avatar asked Dec 11 '12 20:12

Alain Tiemblo


People also ask

How do you find the gcd of two or more integers?

Euclid's algorithm So, Euclid's method for computing the greatest common divisor of two positive integers consists of replacing the larger number by the difference of the numbers, and repeating this until the two numbers are equal: that is their greatest common divisor. So gcd(48, 18) = 6.

How do you find gcd of 3 numbers?

If a and b are two numbers then the greatest common divisor of both the numbers is denoted by gcd(a, b). To find the gcd of numbers, we need to list all the factors of the numbers and find the largest common factor. Therefore, we can conclude that 4 is the highest common factor among all three numbers.

How do you find the gcd of 2 and 3?

FAQs on GCF of 2 and 3 The GCF of 2 and 3 is 1. To calculate the GCF (Greatest Common Factor) of 2 and 3, we need to factor each number (factors of 2 = 1, 2; factors of 3 = 1, 3) and choose the greatest factor that exactly divides both 2 and 3, i.e., 1.


3 Answers

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; };
like image 145
Adrien Gibrat Avatar answered Oct 09 '22 02:10

Adrien Gibrat


Had to do a bit of digging, but this is what I found.

The gcd of three numbers can be computed as gcd(a, b, c) = gcd(gcd(a, b), c), or in some different way by applying commutativity and associativity. This can be extended to any number of numbers.

You could use something like the following:

function multiGCD($nums)
{
    $gcd = getGCDBetween($nums[0], $nums[1]);

    for ($i = 2; $i < count($nums); $i++) { $gcd = getGCDBetween($gcd, $nums[$i]); }

    return $gcd;
}
like image 42
Mr. Llama Avatar answered Oct 09 '22 00:10

Mr. Llama


Take the GCD of numbers 1 and 2, and then the GCD of that and number 3, and so on.

like image 41
Ignacio Vazquez-Abrams Avatar answered Oct 09 '22 02:10

Ignacio Vazquez-Abrams