0
所以我做一個簡單的程序來找到兩個數字之間的最大公約數(LCD),使用歐幾里德算法(http://www.math.jacobs-university.de/timorin/PM/continued_fractions.pdf,第二頁)這是很簡單的。因此,這裏是我創建的功能:簡單的功能,給予意想不到的結果
function largest_common_divider(num1, num2) {
var remainder;
var alpha = num1;
var beta = num2;
for (i = 0; i < 100; i++) {
/* we want to find an "n" such that
n * beta <= alpha < (n + 1) * beta
I initiated n at 1 so that I could use n = 0
as the end condition for my loop */
for (n = 1; n <= 0; n++) {
if (alpha > (n * beta)) {
//still didn't find the n
} else if (alpha == (n * beta)) {
//Hurray! our beta is the lcd
n = 0;
return beta;
} else {
// figure out the remainder
// and set n = 0 to terminate the loop
remainder = alpha - (n - 1) * beta;
n = 0;
}
}
//If we didn't find our lcd, than the previous beta
//become the new alpha (largest number) and the
//the remainder becomes the new beta (smaller number)
alpha = beta;
beta = remainder;
}
}
需要注意的是,在這個節目,我只希望正整數,NUM1> numb2始終。
因此,爲了測試這個功能,我做了這個:
var a = 45; var b = 15;
var bloopidy = largest_common_divider(a,b);
console.log("The largest common divider between " + a + " and " + b + " is: " +
bloopidy);
期待的結果是15,但我得到的是「不確定」。我用所有的小知識,我必須調試這一點,但我不能!我需要幫助的人,任何感激。謝謝!!
男子://這樣一個愚蠢的錯誤! :P謝謝你的回答!歡呼,祝你有美好的一天:) –