[英]looping infinitely through multiple arrays at the same time until a condition is met
我試圖找到給定[3,5]
的兩個數字的最小公倍數,並僅返回可被這兩個數字范圍內的所有數字整除的數字......例如:
let arr = [3,5];
第一個數字倍數應如下所示:
[3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60];
第二個數字倍數應如下所示:
[5,10,15,20,25,30,35,40,45,50,55,60];
最小公倍數應如下所示:
[15,30,45,60];
唯一能被范圍內所有數字整除的數字是60
。
這是我解決這個問題的方法,但我想知道我下面的代碼有什么問題(請解釋,因為我已經厭倦了猜測):
let arr = [3, 5]; let arrRange = []; // [3, 4, 5] // creating a loop to create the range for (var i = arr[0]; i <= arr[1]; i++) { arrRange.push(i); } let f = arr[0], s = arr[1], c = 0, result = 0, firstMultiples = [], secondMultiples = [], leastCommonMultiples = []; // This function is made if the number least Common number is divisible by all the numbers in the "arrRange" function isDivisible(num) { for(var i = 0; i < arrRange.length; i++) { if(num % arrRange[i] != 0) { return false; } } return true; } while(true) { firstMultiples.push(f); secondMultiples.push(s); f = f + arr[0]; s = s + arr[1]; let vals = secondMultiples.values(); for(let val of vals){ if( firstMultiples.includes(val) ) { leastCommonMultiples.push(val); } } let cmlVals = leastCommonMultiples.values(); for(let cmlVal of cmlVals){ if(isDivisible(cmlVal)) { result += cmlVal; break; } } c++; } console.log(result);
要修復它,請將 while 循環從while (true) {/*code*/};
更改為 to while(isDivisible(cmlVal) == true) {/*code*/};
並刪除if(isDivisible(cmlVal)) {/*code*/ break;}
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.