用js遞歸實現最大公約數與最小公倍數


先說一說關於最大公約數與最小公倍數怎么算的;

兩個數A B相除取余C,第二個數B除C取余,直到整除,那么被除數被最小公倍數。(輾轉相除法);

最小公倍數:兩個數相乘除以最大公約數;

邏輯流程圖

按照題意求最大公約數看到判斷循環首先想到的就是if、while、for;

好,那就先用while實現以下

先放簡單的html

<p>輸入兩個數</p>
<input type="text" id="num1" >
<input type="text" id="num2">
<input type="button" id="da" value="求最大公約數">
<input type="button" id="xiao" value="求最小公倍數">

然后是js

        //最大公約數
        function gcd( x ,  y){  
        var max,min,temp;  
        max = x > y ? x : y ;  
        min = x < y ? x : y ;  
        while( max % min ){  
  
            temp = max % min;  
            max = min;  
            min = temp;  
        }  
        return min;  
        }  
        //最小公倍數  
        function lcm(  x ,  y ){  
            return x*y/gcd(x,y);  
        }  
        document.getElementById('da').onclick = function () {
            alert("最小公約數為:"+gcd(document.getElementById('num1').value,document.getElementById('num2').value));
        }

用while實現還是很麻煩的!

我們現在用遞歸實現一下

        function digui(m , n){
            return m%n==0?(n):(digui(n,m%n));
        }
        document.getElementById('da').onclick = function () {
            alert("最小公約數為:"+digui(document.getElementById('num1').value,document.getElementById('num2').value));
        }
        document.getElementById('xiao').onclick = function () {
            var da = (document.getElementById('num1').value*document.getElementById('num2').value)/(digui(document.getElementById('num1').value,document.getElementById('num2').value));
            alert("最小公倍數為:"+da);
        }

實現部分只有短短的一行!

邏輯流程圖

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM