Smallest Common Multiple timeout issue

Tell us what’s happening:
Hey all,

So I was doing the smallest common multiple challenge. I know this solution isn’t the most elegant but it works on my local machine (using Node.js from the command line). However, when submitted on FCC it doesn’t work. I suspect it is because the code is inefficient and is taking too long of a time to run. Is that a reasonable assumption?

Your code so far

function smallestCommons(arr) {
  var reducer = function(accumulator, cv) { return accumulator * cv; }; 
  var second_reducer = function(accumulator, cv) { return accumulator + cv; }; 
  var nums = [];
  var largest = arr[0] > arr[1] ? arr[0] : arr[1];
  var smallest = arr[0] < arr[1] ? arr[0] : arr[1];
  for (var i = smallest; i <= largest; i++) {
    nums.push(i);
  }
  var commonMultilpe = nums.reduce(reducer);
  for (var index = 1; index < commonMultilpe; index++) {
    var values = [];
    for (var num = 0; num < nums.length; num++) {
      values.push(index % nums[num]);
  }
    if (!values.reduce(second_reducer) > 0) { return index; }
  }
  return commonMultilpe;
}


smallestCommons([1,5]);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/smallest-common-multiple

Your code passes all tests when I put // noprotect at the top of the page so, yes it passes all tests but, it’s very slow as you admitted. Go back later and refine it.

https://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/

http://bigocheatsheet.com/

1 Like

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.

Thank you.