寻找大于2个整数的GCD(最大公约数)吗? [英] Look for the GCD (greatest common divisor) of more than 2 integers?
本文介绍了寻找大于2个整数的GCD(最大公约数)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经有一个可以找到2个数字的GCD的函数.
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;
}
但是现在,我想扩展此功能以找到N点的GCD.有什么建议吗?
But now, I would like to extend this function to find the GCD of N points. Any suggestion ?
推荐答案
还有一种更优雅的方法:
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
您可以在PHP 5.3中使用闭包:
You can use a closure in PHP 5.3 :
$gcd = function ($a, $b) use (&$gcd) { return $b ? $gcd($b, $a % $b) : $a; };
这篇关于寻找大于2个整数的GCD(最大公约数)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文