Search code examples
javascriptfizzbuzz

Javascript Fizzbuzz Issue


I'm trying to do some simple tests to help further my javascript knowledge (which is quite fresh). Goal 1 is to print numbers from 1-100 that aren't divisible by 5 or 3.

I tried the following:

for (var i = 1; i <= 100; i ++) 
{
    if (i%3 !== 0 || i%5 !== 0){
        console.log(i);
    }

}

This logs EVERY number from 1-100, and I can't tell why. Probably the simplest simplest questions here but it's doing my head in!


Solution

  • I think you mean &&, not ||. With ||, you're basically testing to see if the number is not divisible by 3 or by 5 - only if a number is divisible by both do you reject it (in other words, multiples of 15).

    The typical answer to FizzBuzz is:

    if( i%3 == 0 && i%5 == 0) FizzBuzz
    elseif( i % 3 == 0) Fizz
    elseif( i % 5 == 0) Buzz
    else number
    

    So to get directly to the number you need for i%3==0 to be false AND i%5==0 to be false. Therefore, you want if( i%3 !== 0 && i%5 !== 0)