同时通过多个数组无限循环直到满足条件

问题描述 投票:2回答:1

我正在尝试找到给定[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);
javascript
1个回答
0
投票

要修复它,请将while循环从while (true) {/*code*/};更改为 while(isDivisible(cmlVal) == true) {/*code*/};,然后删除 if(isDivisible(cmlVal)) {/*code*/ break;}

© www.soinside.com 2019 - 2024. All rights reserved.