LoginSignup
0
0

ユークリッドの互除法で最小公倍数を求める。

Last updated at Posted at 2023-08-21

ユークリッドの互除法で最小公倍数も求めることができる。
まず、前回えんじぇる、が作った最大公約数を求める関数。

ユークリッドの互除法で最大公約数を求める

これを使い、($a*$b)/最大公約数で求めることが出来る。

<?php
    $x=0;
    $y=0;
    [$a,$b]=preg_split('/ /', trim(fgets(STDIN)));
    function one($a,$b){
        if($a==0 || $b==0){
            return three($a,$b);
        }elseif($a!=0 && $b!=0){
            return two($a,$b);
        }    
    }
    function two($a,$b){
        if($a>$b){
            $x=$a%$b;
            $a=$x;
            if($a==0){
                return three($a,$b);
            }else{
                return two($a,$b);
            }
        }elseif($a<$b){
            $y=$b%$a;
            $b=$y;
             if($b==0){
                return three($a,$b);
            }else{
                return two($a,$b);
            }
        }
    }    
    function three($a,$b){
        if($a==0){
            return $b;
        }elseif($b==0){
            return $a;
        }    
    }
    $kotae = ($a*$b)/one($a,$b);
    echo $kotae;
?>

しかし、前回、@dgcdsbsd2さんに教えて頂いた方法を使うと、もっと簡単にできると思ったので、下記を試してたみた。

23年8月25日編集
$bも変化していることを忘れていた。
$a,$bの初期値を$x,yに保存。
無事に最小公倍数が出た。

<?php
//結果の変数の初期化
$ans;
[$a, $b] = preg_split('/\s+/', trim(fgets(STDIN)));
//$a、$bの初期値を$x,$yに保存
$x=$a;
$y=$b;
//$bが0になるまで$aに$a%$bの値を入れ替えていく
while($b) {
  [$a, $b] = [$b, $a % $b];
}
$ans=($x*$y)/$a;
echo $ans;
?>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0