Adil Ahmed
Adil Ahmed

Reputation: 435

Smallest Common Multiple [Javascript Challenge]

Question: Find the smallest common multiple of the provided parameters that can be evenly divided by both, as well as by all sequential numbers in the range between these parameters.

The range will be an array of two numbers that will not necessarily be in numerical order.

For example, if given 1 and 3, find the smallest common multiple of both 1 and 3 that is also evenly divisible by all numbers between 1 and 3, i.e. divisible by 1, 2 and 3. The answer here would be 6.

function smallestCommons(arr) {
  var max=Math.max(...arr);
  var min=Math.min(...arr);
  var flag = 0;
  var i = min;
    while(true)
    {for(var j=min;j<=max;j++)
        {if(i%j!=0)
          {flag=1;
          break;}
        }
      if(flag==0)
        {flag=5;
        break;
        }
      i++;
    }
console.log(i);
}

smallestCommons([1,5]);

For somereason my solution seems to go crazy and go into infinite looping. Although if I initialize var i to 60 (which is the desired output for this specific case i.e.[1,5]) the solution seems to be fine. Any fixes or guesses?

Upvotes: 1

Views: 996

Answers (2)

Adil Ahmed
Adil Ahmed

Reputation: 435

I did figure out the solution, thanks to the two programming geeks in the main comments sections.

function smallestCommons(arr) {
  var max=Math.max(...arr);
  var min=Math.min(...arr);
  var flag = 0;
  var count = 0;
  var i = 1;
    while(1){
      for(var j=min;j<=max;j++)
      {if(i%j!=0)
        {flag=1;
        break;}
      if(j==max){
        flag=0;
      }
      }
      if(flag==0){
        break;
      }
      i++;
 }
console.log(i);
}


smallestCommons([10,2]);

Upvotes: 0

blex
blex

Reputation: 25634

@Kevin has given a pretty good explanation of why it's not working. Your loop will only stop if flag is 0. But once it has been set to 1, you never reset it to 0.

function smallestCommons(arr) {
  var max = Math.max(...arr);
  var min = Math.min(...arr);
  var flag = 0;
  var i = min;
  while (true) {
    for (var j = min; j <= max; j++) {
      if (i % j != 0) {
        flag = 1;
        break;
      }
    }
    if (flag == 0) {
      return i; // Return that common value
    }
    flag = 0; // Reset the flag
    i++;
  }
}

console.log(smallestCommons([1, 5]));

And here is an alternative way:

function smallestCommons(arr) {
  const min = Math.min(...arr),
        max = Math.max(...arr),
        range = createRange(min, max);
        
  let current = max;

  while (true) {
    const isFullyDivisible = range.every(n => current % n === 0);
    if (isFullyDivisible) {
      return current;
    }
    current++;
  }
}

function createRange(min, max) {
  return new Array(max - min + 1).fill(null).map((_, i) => min + i);
}

console.log(smallestCommons([1, 3]));  // 6
console.log(smallestCommons([5, 1]));  // 60
console.log(smallestCommons([1, 10])); // 2520

Upvotes: 1

Related Questions