©
This document uses PHP Chinese website manual Release
(PHP 4 >= 4.0.4, PHP 5, PHP 7)
gmp_gcd — Calculate GCD
$a
, GMP $b
)
Calculate greatest common divisor of a
and
b
. The result is always positive even if
either of, or both, input operands are negative.
a
可以是一个 GMP 数据 resouce ,或一个可以转换为数值的字符串。
b
可以是一个 GMP 数据 resouce ,或一个可以转换为数值的字符串。
A positive GMP number that divides into both
a
and b
.
Example #1 gmp_gcd() example
<?php
$gcd = gmp_gcd ( "12" , "21" );
echo gmp_strval ( $gcd ) . "\n" ;
?>
以上例程会输出:
3
[#1] sean__remove__ at eternalrise_r_emove__ dot com [2008-11-10 19:50:01]
Here's my solution for getting the GCD of several numbers.
<?php
function gcd($a, $b)
{
if ($a == 0 || $b == 0)
return abs( max(abs($a), abs($b)) );
$r = $a % $b;
return ($r != 0) ?
gcd($b, $r) :
abs($b);
}
function gcd_array($array, $a = 0)
{
$b = array_pop($array);
return ($b === null) ?
(int)$a :
gcd_array($array, gcd($a, $b));
}
?>
[#2] limas at kultur-online dot at [2007-12-01 10:44:18]
The previous function returns just 1 under php 5.2.4 but the following seems to work (m>0,n>0):
function gcd($m,$n)
{
$_m=$m;$r=1;
if($m<$n){$t=$m;$m=$n;$n=$t;}
while($r)
{
$r=(floor($m/$n)*$n)-$m;
$_n=$n;$n=$r;$m=$_m;
}
return abs($_n);
}
[#3] bigkm1 at gmail dot com [2006-08-25 21:33:03]
here is an elegant recursive solution
<?php
function gcd($a,$b) {
return ($a % $b) ? gcd($b,$a % $b) : $b;
}
?>
[#4] scr02001 at student dot mdh dot se [2003-08-16 06:58:39]
If you do not consier a or b as possible negative numbers, a GCD funktion may return a negative GCD, wich is NOT a greatest common divisor, therefore a funktion like this may be better. This considers the simplyfying of (-3)-(-6) where gcd on -3 and -6 would result in 3, not -3 as with the other function. (-3)-(-6) is (-1)-(-2) NOT (1)-(2)
function eGCD($a,$b){
if($a < 0) $a=0-$a;
if($b < 0 ) $b=0-$b;
if($a == 0 || $b == 0) return 1;
if($a == $b) return a;
do{
$rest=(int) $a % $b; $a=$b; $b=$rest;
}while($rest >0);
return $a;
}
[#5] Ludwig Heymbeeck [2003-01-12 10:33:08]
The following function is more accurate:
function GCD($num1, $num2) {
while ($num2 != 0){
$t = $num1 % $num2;
$num1 = $num2;
$num2 = $t;
}
return $num1;
}
[#6] x-empt-php dot net at ispep dot cx [2002-07-06 23:16:36]
No need to compile gmp functions in just for the GCD function... use this one instead:
function GCD($num1, $num2) {
if ($num1 < $num2) {
$t = $num1;
$num1 = $num2;
$num2 = $t;
}
while ($t = ($num1 % $num2) != 0) {
$num1 = $num2;
$num2 = $t;
}
return $num2;
}