1

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!

4

2 に答える 2

4

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)

于 2012-12-06T04:00:42.980 に答える
-1

I attacked this the same was as Niet the Dark Absol:

for (var n = 1; n <= 100; n++) {
    if (n % 3 == 0 && n % 5 == 0)
        console.log("FizzBuzz");
    else if (n % 3 == 0)
        console.log("Fizz");
    else if (n % 5 == 0)
        console.log("Buzz");
    else
            console.log(n);
}

However, you can also do it this way:

for (var n = 1; n <= 100; n++) {
    var output = "";
    if (n % 3 == 0)
        output += "Fizz";
    if (n % 5 == 0)
        output += "Buzz";
    console.log(output || n);
}

One of the hardest parts of learning JavaScript - or any language - for me is understanding solutions can come in many ways. I like the first example more, but it's always good to keep thinking and look at other options.

于 2015-01-02T00:13:00.107 に答える