兩個或三個數字的LCM我使用下面的代碼來確定兩個或三個數字的GCD:計算在JavaScript
$('#calc').click(function(){
Math.GCD = function(numbers) {
for (var i = 1 ; i < numbers.length ; i++){
if (numbers[i] || numbers[i] === 0)
numbers[0] = twogcd(numbers[0], numbers[i]);
}
return numbers[0];
function twogcd(first, second) {
if (first < 0) first = -first;
if (second < 0) second = -second;
if (second > first) {var temp = first; first = second; second = temp;}
while (true) {
first %= second;
if (first == 0) return second;
second %= first;
if (second == 0) return first;
}
}
};
Math.LCM = function(first,second) {
return first * (second/this.GCD(first, second)); // CANNOT FIGURE OUT HOW TO EXTEND THIS TO THREE #s
};
var first = document.getElementById("first").value;
var second = document.getElementById("second").value;
var third = document.getElementById("third").value;
var numbers = [first,second,third];
var GCDresult = Math.GCD(numbers);
alert(GCDresult);
});
通知有關於LCM的功能。
這裏是我的HTML:
<FORM NAME="sci-calc" method="POST" id="sci-calc">
<button TYPE="button" ID="calc">CALC</button>
<input type="text" name="stuff[]" class="input-field" id="first"/>
<input type="text" name="stuff[]" class="input-field" id="second"/>
<input type="text" name="stuff[]" class="input-field" id="third"/>
</FORM>
而且小提琴:https://jsfiddle.net/59z28rpk/
我試圖擴展這個功能,因此,它可以計算的相同的兩個或三個用戶提供輸入的LCM,但我不能爲我的生活得到它的權利。我是JavaScript的新手,非常感謝任何幫助。請注意,如果一個字段留空,它也應該從計算中省略,就像GCD所做的那樣。
請問一個 「LCM」 和 「GCD」 是什麼,或者是誰? –
@DavidThomas,最小公倍數和最大公約數。 –
@妮娜:非常感謝你! :) –