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.
//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].