1. 最大公约数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;
    }
    View Code
  2. 最小公倍数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 }
    View Code
posted on 2017-03-28 16:46  jade640  阅读(114)  评论(0编辑  收藏  举报