- 最大公约数gcd(greatest common divisor)
<?php //获取两个数的最大公约数greatest common divisor //辗转相除法。另外还可以采用更相损减法 function gcd($num1,$num2){ if($num1 < $num2) gcd($num2, $num1); while($num2 != 0){ $tmp = $num1%$num2; $num1 = $num2; $num2 = $tmp; } return $num1; }
- 最小公倍数lcm(lowest common multiple)
1 <?php 2 //获取两个数的最大公约数greatest common divisor 3 //辗转相除法。另外还可以采用更相损减法 4 function gcd($num1,$num2){ 5 if($num1 < $num2) gcd($num2, $num1); 6 while($num2 != 0){ 7 $tmp = $num1%$num2; 8 $num1 = $num2; 9 $num2 = $tmp; 10 } 11 return $num1; 12 } 13 //求最小公倍数 14 function lcm($num1, $num2){ 15 return $num1*$num2/gcd($num1, $num2); 16 }