I have to find the lcm of all the numbers 1 through and including 20, and I came up with this code. It, although is inefficient and also comes up with an answer that is 2 more than the correct answer. Could anyone tell me why?
//variable used to shut off the while loop.
divisable = false;
var i = 2;
//function to prove if the number is a lcm
var isDivisable = function(number){
for(var i = 2; i<=20; i++){
if(number%i !== 0){
divisable = false;
// added the break to shut down the function,
// as no other loops need to be counted
break;
}else{
divisable = true;
}
}
};
while(!divisable){
isDivisable(i);
i+=2;
}
What was wrong with my code?
isDivisiblekeeps executing untildivisibleis set to true (from your while loop), where yourforloop will do all that for you. Also, you're puttingi+=2in the while loop, which adds 2 to the result, after your program stops spazzing out from executingisDivisibleso many times.How to fix?
Remove the while loop, and just call
isDivisablemanually.The result is that
iwill be the multiple.Additional Notes
isDivisibleis spelled wrong in your code, asisDivisable.