Solution: Smallest Common Multiple - freeCodeCamp (Intermediate Algorithm Scripting)

 Smallest Common Multiple


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. The answer here would be 6.


SOLUTION:


function smallestCommons(arr) {
  arr = arr.sort((a,b) => a-b)
  let arr1 = []
  for(let i=arr[0];i<=arr[arr.length - 1];i++) {
    arr1.push(i)
  }

  let prod = arr1[arr1.length - 1]
  let i = 1;
  while(!checkFor(arr1, prod)) {
    prod = arr1[arr1.length - 1] * i
    i++;
  }
  return prod;
}

function checkFor(arr, prod) {
  for(let i=0;i<arr.length;i++) {
    if(prod%arr[i] != 0) {
      return false;
    }
  }
  return true;
}

smallestCommons([1,5]);


Smallest Common Multiple


Click here to go to the original link of the question.

Post a Comment

Previous Post Next Post