理解while循环代码以找到最小的公共倍数

时间:2017-12-21 23:12:17

标签: javascript while-loop

在此代码中,是否有人可以在循环循环中逐行解释/分解代码?我正在经历“找到最小的常见倍数”。对freecodecamp的挑战。据我所知,我还添加了评论。

function smallestCommons(arr) {
  var min = Math.min(arr[0], arr[1])
  var max = Math.max(arr[0], arr[1])
  var range = []

  for(var i = min; i<=max; i++){
    range.push(i); //array of numbers between min and max
  }

  var a = Math.abs(range[0]) //absolute position of negative nums from 0

  for(var j=1; j<range.length; j++){
    var b = Math.abs(range[j]); //iterating range array
    var c = a;

    while(a && b){ //filtering 0. will continue looping as long as a and b is NOT 0
      if(a>b) { 
        a = a%b; //then we will change the value of a to the remainder of a/b
      } else {
        b= b%a;  //changing the value of b 
      }
    }

    a = Math.abs(c*range[j] /(a + b)); 
  }

  return a;
}

smallestCommons([1,5]);

1 个答案:

答案 0 :(得分:1)

基本上算法循环遍历所有数字,并通过将当前运行的SCM乘以仅存在于下一个数字中的任何新因子来计算运行中的最小公倍数(例如,将当前数字除以GCD后剩余的因子(运行) SCM,当前号码)。

function smallestCommons(arr) {
// find the smallest common multiple of all the integers from arr[0] to arr[1]

  var min = Math.min(arr[0], arr[1]); // get the starting number
  var max = Math.max(arr[0], arr[1]); // get the ending number
  var range = []; // array of all the numbers

  for(var i = min; i<=max; i++){
    range.push(i); //array of numbers between min and max
  }

  var a = Math.abs(range[0]); // start with first number

  for(var j=1; j<range.length; j++) { // compute over remaining numbers in range
    var b = Math.abs(range[j]); // get the next number to process
    var c = a; // remember starting point for end

    while(a && b){ // find the GCD of a & b
      if(a>b) { 
        a = a%b;
      } else {
        b = b%a; 
      }
    }
    // the GCD will be in a or b, whichever is not zero

// compute the smallest common multiple of the numbers from range[0] to range[j]
// by multiplying in the remaining factors after removing the GCD
// which is range[j] / (a+b) since either a or b is the GCD
    a = Math.abs(c*range[j] /(a + b));
  }

  return a;
}