0

I've been stuck in this free code camp algorithm and really need some help.

this is what i am supposed to do:

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.

e.g. for 1 and 3 - find the smallest common multiple of both 1 and 3 that is evenly divisible by all numbers between 1 and 3.

i have to check weather each value in my arr is divisible by my common multiple and really haven't been able to accomplish it.

this is what i have so far:

function smallestCommons(arr) {
  arr = arr.sort();
  var number = arr[0];
  var secArr = [];
  // create a new list with all values to check against.
  while (number >= arr[0] && number <= arr[1]) {
    secArr.push(number);
    number++;
  }

  var commonMultiple = 1;
  var isTrue = true;

  function isDivisible(item) {
    if (item % commonMultiple === 0) {
      return true;
    }
    else {
      return false;
    }
  }

  while (isTrue) {
    commonMultiple++;
    if (secArr.every(isDivisible)) {
        isTrue = false;
    }
  }
  return commonMultiple;
}

smallestCommons([5,1]);

I tried to solve this problem, with Euclid's algorithm and thought it was very hard, tried with for loops and couldn't, I'm currently trying to check with .every but it says i have an infinite loop.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • 1
    I think a duplicate of : http://stackoverflow.com/questions/31302054/how-to-find-the-least-common-multiple-of-a-range-of-numbers – JonSG Jun 29 '16 at 02:39

2 Answers2

0

So here's my solution, I hope you find it illuminating:

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

  var smallestCommon = min * max;

  var doneCalc = 0;

  while (doneCalc === 0) {
    for (var i = min; i <= max; i++) {
      if (smallestCommon % i !== 0) {
        smallestCommon += max;
        doneCalc = 0;
        break;
      }
      else {
        doneCalc = 1;
      }
    }
  }

  return smallestCommon;
}
Yup.
  • 1,883
  • 21
  • 18
-1

function smallestCommons(arr) {
  arr.sort((a,b)=>a-b);
  var sm = arr[0];
  var lg = arr[1];
  var j = 0;
  var mul;
  var checkNumber = function(num) {
    for(var i = sm; i <= lg; i++) {
       if(num%i !== 0)
          return false;
    }
    return true;
  };
  
  do{
    j++;
     mul = sm * lg * j;
    
  } while(checkNumber(mul) !== true);
  
  
  return mul;
}


console.log(smallestCommons([1,5]));
Icepickle
  • 12,689
  • 3
  • 34
  • 48
  • Please add why your code fixes the problem the OP has. Just having the code working is not always enough if the user doesn't know what he did wrong or why your answer fixes his problem. Please see [how to answer](https://stackoverflow.com/help/how-to-answer) – Icepickle Jun 29 '17 at 22:05