What was wrong with my code?
isDivisible
keeps executing until divisible
is set to true (from your while loop), where your for
loop will do all that for you. Also, you're putting i+=2
in the while loop, which adds 2 to the result, after your program stops spazzing out from executing isDivisible
so many times.
How to fix?
Remove the while loop, and just call isDivisable
manually.
var isDivisable = function(number){
if (number % 1 == 0) {
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;
alert(i);
}
}else
{
alert('Your number is not divisible.');
}
};
isDivisable(6); //Replace with a number
The result is that i
will be the multiple.
Additional Notes
isDivisible
is spelled wrong in your code, as isDivisable
.