Smallest common multiple - last test

Smallest common multiple - last test
0

#1

Hello, can anyone point my bug? Only last test doesn’t pass but it passed when I run it on notepad++ with chrome.

smallestCommons([23, 18]) should return 6056820.

function smallestCommons(arr) {
  var sorted = arr.sort(function(a,b) {
		return a-b;
	});
	console.log(sorted);
	var min = sorted[0];
	console.log(min);
	var max = arr.reduce(function(a,b) {
		return (a > b ? a : b);
	});
	console.log(max);
	var all = [];
	for(var i = min; i <= max; i++) {
		all.push(i);
	}
	console.log(all);
	var maxMultiple = all.reduce(function(val, val2) {
		return val*val2;
	});
	console.log(maxMultiple);
	console.log(max);
	
	
	for(var a = max; a <= maxMultiple; a++ ) {
		for(var b = min, counter = 0; b <= max; b++) {
			if(a%b ===0) 
		{
			counter++; 
			if(counter === ((max-min)+1)) {
				
				return a;
				
			}
		}
		else {
			counter = 0;	
		}
				
			}
		}
  console.log(a);
  return a;
}


smallestCommons([1,5]);

#2

The code is not passing because the editor thinks there’s probably an infinite loop in your code, but your code’s reasonably fast enough. Add // noprotect at the top of your code to disable the infinite loop checker.


#3

I had the same problem in my solution. So, if FCC editor thinks there is an infinite loop, it means that solution is not good as far and therefore not performatic, right?

this is my code:

function smallestCommons(arr) {
  //sort arr from smaller to bigger
  arr.sort(function(n1, n2) {
    return n1 - n2;
  });

  //set smaller and bigger variables
  var smaller = arr[0];
  var bigger = arr[1];
  
  // the SCM (Smallest Common Multiple)
  var scm;

  //loop to test possible number
  //this loop starts from bigger + 1 to avoid unecessary loops
  var notFound = true;
  for(var i = 1; notFound; i++) {
    //starting to test the possible number (i) in range of smaller to bigger
    var divisibleInRange = true;
    for(var j = smaller; j <= bigger; j++) {
      if(i % j == 0) {
         // if the possible number (i) is divisible, continue loop to test next number in range
        continue;
      } else {
        // if any number in range not be divisible, stop test inside range
        divisibleInRange = false ;
        break;
      }
    }

    //if the possible number is divisible for all number in range, so you found SCM and therefore stop loop
    if(divisibleInRange) {
      scm = i;
      notFound = false;
    }
  }

  return scm;
}

#4

Not quite. The solution can be perfectly performant, it’s just that, in certain circumstances, the loop can continue going forever. So in yours, what happens if the number is not divisible (ie notfound stays true)? Is it actually ever likely to happen, and if so, how could you guard against it happening - this is what the warning is asking you to consider.


#5

Good point! Depending the case it could become an infinite loop.

Thanks for feedback.