Home  >  Article  >  Backend Development  >  How to find the greatest common divisor and least common multiple in PHP

How to find the greatest common divisor and least common multiple in PHP

墨辰丷
墨辰丷Original
2018-05-22 10:17:046264browse

This article mainly introduces the method of finding the greatest common divisor and the least common multiple in PHP programming, involving related calculation skills of PHP mathematical calculations. Friends in need can refer to it

The details are as follows:

//求最大公约数
function max_pisor($a,$b)
{
   $n = min($a, $b);
   for($i=$n; $i>1; $i--)
   {
     if (is_int($a/$i)&&is_int($b/$i))
     {
     return $i;  //此处如果用echo $i;则输出结果为432;故应区分echo、return的区别
     }
   }
   return 1;
}
//求最小公倍数
function  min_multiple($a, $b)
{  if($b==0)   //一定要考虑除数不能为零
   {
     return $b;
   }else{
   $m = max($a, $b);
   $n = min($a, $b);
   for($i=2; ; $i++)
   {
     if (is_int($m*$i/$n))
     {
       return $i;
     }
   }
}
   return $a*$b;
}
//辗转相除法求最大公约数
 function max_pisor2($a, $b)
{
   if($b==0)
   {
     return $a;
   }
   else
   {
     return max_pisor2($b,($a%$b));
   }
}
//加减法求最大公约数
function max_pisor3($a, $b)
{
   if ($a == $b)
   {
     return $a;
   }
   elseif($a > $b)
   {
     $a = $a-$b;
   }
   else
   {
     $b = $b-$a;
   }
   return max_pisor3($a, $b);
}

Related recommendations:

##JS obtains the least common multiple and the greatest common divisor

How to achieve the largest common divisor of two integers?

2. Find the largest common divisor and the least common multiple (maximum ## of m and n #Common divisor: Euclidean division method)

# #

The above is the detailed content of How to find the greatest common divisor and least common multiple in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn