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

时间:2017-10-09 00:58:48

标签: javascript

我试图找到给定[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);
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

要解决此问题,请将while循环从while (true) {/*code*/};更改为 while(isDivisible(cmlVal) == true) {/*code*/};,然后删除 if(isDivisible(cmlVal)) {/*code*/ break;}