Function using loop and if inside

Hi, I am doing the challenge.

I am trying to check if the number put in is divisible by all the number in the array and return true if so.

However, it only check if the number is divisible by the 1st number and return true immediately.

Your code so far


function smallestCommons(arr) {
//sort array small - big
arr.sort((a,b)=> a===b? 0: a-b<0? -1:1);
//put all the number in an array
let allNum = [];
for (let i=arr[0]; i<=arr[1]; i++){
 allNum.push(i);
}
//Calculate the multiple of all number
let result = 1;
for(let i=0; i<allNum.length; i++) {
 result = result*allNum[i];
}
//Create a function to check if a number is divisible by all number in the array
function checkCom(num) {
for(let j=allNum[0]; j<allNum[allNum.length-1]; j++) {
  if (num % j == 0) {return true;} 
}
 return false;
}
//Check and return the number if it meet the function
for (let i=1; i<result; i++) {
 if (checkCom(i)) { return i  };
}
}
console.log(smallestCommons([98,14]));

Your browser information:

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

Challenge: Smallest Common Multiple

Link to the challenge:

What about flipping the logic around? Return false if the number is not divisible?

Unfortunately, when I try that, it returns 1 .

What is the code for that?

//Create a function to check if a number is divisible by all number in the array
function checkCom(num) {
for(let j=allNum[0]; j<allNum[allNum.length-1]; j++) {
if (num % j !== 0) {return false;}
}
return true;
}
//Check and return the number if it meet the function
for (let i=1; i<result; i++) {
if (!checkCom(i)) { return i };
}
}
console.log(smallestCommons([98,14]));

// Create a function to check if a number is divisible by all number in the array
function checkCom(num) {
  for (let j = allNum[0]; j <= allNum[allNum.length-1]; j++) {
    if (num % j !== 0) {
      return false;
    }
  }
  return true;
}

I added a small change (do you see it?) in the for loop, but this correctly checks if num is divisible by the numbers from allNum[0] to allNum[allNum.length-1].

What do you mean by “returns 1”?

After implementing the code. The console.log() I get was 1 which was incorrect for this challenge requirement.

When I get the change I showed you, I get

Potential infinite loop detected on line 23. Tests may fail if this is not changed.
undefined

I suspect this approach is way to slow to work.

I would be happy to help you brain storm a new approach though.