Tell us what’s happening:
Only last case is not working because of infinite loop. I don’t know how much should I increment i ?? When I write i++ instead of i+=g its working fine in the browser but not in the FCC console. I put var g because I think it shouldn’t be incremented by 1 every time. How much should I increment variable i ?
Your code so far
function smallestCommons(arr) {
var i=1, j=0, g=0, b=0, newArr=[];
for(i=Math.min(arr[0],arr[1]); i <= Math.max(arr[0],arr[1]); i++){
newArr.push(i);
}
newArr.reverse();
i=1;
while(true){
g = 0;
j = 0;
while(j < newArr.length){
if(i % newArr[j] === 0)
g++;
if(g === newArr.length){
b = i;
break;
}
j++;
}
if(b===i)
break;
i += g;
}
return b;
}
smallestCommons([1,13]);
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36.
give this a try, I added some simple ways to make it more efficient, but still keep your code.
function smallestCommons(arr) {
var i=1, j=0, g=0, b=0, newArr=[];
for(i=Math.min(arr[0],arr[1]); i <= Math.max(arr[0],arr[1]); i++){
newArr.push(i);
}
newArr.reverse();
// start at the highest value for i, we know i has to be divisible by the max value, so it has to at least be that
i=Math.max(arr[0],arr[1]);
//setting this as true works, but it may set off some alarms as it could be an inifinte loop, setting this will make it run as long as b doesn't equal i
while(b!=i){
g = 0;
j = 0;
while(j < newArr.length){
if(i % newArr[j] === 0){
g++;
}
// I added an else statement here, as soon as we know there is a remainder for one value in the array, that i is no longer valid, and we can move to the next one. We also know that since it must be divisible by the max number we can increase it by the max number.
else {
i += Math.max(arr[0],arr[1]);
break;
}
if(g === newArr.length){
b = i;
break;
}
j++;
}
}
return b;
}
smallestCommons([23, 18])