0

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;
}
UNEVERIS
  • 249
  • 1
  • 2
  • 8
  • 1
    You cannot say `var i = 2` if you define it in your loop – Cilan Jan 06 '14 at 21:56
  • right, I'm sorry I used j instead of i, just didn't transfer it over to this. Look at it as if that is not a problem. – UNEVERIS Jan 06 '14 at 21:57
  • 3
    LCM(a, b) = (a * b) / GCD(a, b) – cHao Jan 06 '14 at 21:58
  • `answer that is 2 more than the correct answer`: The line `i+=2` might have something to do with that! After you call `isDivisable` you are incrementing `i` again before you test the loop condition to see if you should quit. I'd reverse those two lines and start `i` at `0` instead. – Matt Burland Jan 06 '14 at 22:00

2 Answers2

1

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.

Cilan
  • 13,101
  • 3
  • 34
  • 51
0

For fun:

[0, 1, 2, 3, 4, 5, 6].map(function(i) {
    if(this % i == 0)
        alert(i);
}, 6);

Should alert when the value contained in the array ([0, . . ., 6]) is a multiple of the value passed to the callback (in this case 6). See Array.prototype.map().

http://jsfiddle.net/5nSE4/1/

Julio
  • 2,261
  • 4
  • 30
  • 56