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 ?
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.
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.
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.
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; };
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;
}
Take the GCD of numbers 1 and 2, and then the GCD of that and number 3, and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With