html中求兩個函數最大公約數和最小公倍數?
<body>
<h1>求最大公約數</h1>
<span>輸入第一個數:<input type="text" id="first" value="3"></span><br>
<span>輸入第一個數:<input type="text" id="second" value="5"></span><br>
<button οnclick="gcd();">公約數</button>
<button οnclick="lcm();">公倍數</button>
<hr>
<div id="result">
</div>
</body>
<script>
function gcd(){
var temp=second;
//獲取輸入框的值
var first=document.getElementById('first').value;
var second=document.getElementById('second').value;
//if (first>second) {
//var temp;
while(second!=0){
temp=first%second;
first=second;
second=temp;
}
//輸出最大公約數
document.getElementById('result').innerHTML=first;
}
function lcm(){
//獲取輸入框的值
var first=document.getElementById('first').value;
var second=document.getElementById('second').value;
var temp1,lcm;
//判斷輸入的兩個值大小,將較大的數復制給temp
if (first>second) {
temp1=first;
}
else
temp1=second;
//循環判斷是否能被兩個數整除,當整除時,跳出循環
while(true){
if (temp1%first==0 && temp1%second==0) {
lcm=temp1;
break;
}
else
temp1++;
//return lcm;
}
//輸出最小公倍數
document.getElementById('result').innerHTML=lcm;
}
</script>