tommo
tommo

Reputation: 609

Modulus and remainders - Javascript

Sorry for the two questions in such a short amount of time lol Why do 1%15, 3%15, 5%15 have 0 remainder? I may be rusty on math but I thought they should have remainders.

May be unnecessary but here is the code:

for (i = 1; i <= 20; i++) {
    if (i % 15 === 0) {
        console.log("FizzBuzz");
    }
    else if (i % 3 === 0) {
        console.log("Fizz");
    }
    else if (i % 5 === 0) {
        console.log("Buzz");
    }
    else {
        console.log(i);
    }
}

and output:

**FizzBuzz** 
2
**FizzBuzz** 
4
**FizzBuzz**
Fizz 
7 
8 
Fizz 
Buzz 
11 
Fizz 
13 
14 
FizzBuzz 
16 
17 
Fizz 
19 
Buzz

Upvotes: 1

Views: 5706

Answers (2)

Robert Mark Bram
Robert Mark Bram

Reputation: 9663

Because you are not asking 1%15, 3%15, 5%15... you are asking 15%1, 15%3, 15%5. :)

To clarify, this should get you the result you are after.

for(i = 1; i <= 20; i++) {
   if(i%15 === 0) { 
      console.log("FizzBuzz"); 
   } else if(i%3 === 0) { 
      console.log("Fizz"); 
   } else if(i%5 === 0) { 
      console.log("Buzz"); 
   } else { 
      console.log(i); 
   }
}

Output:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz

Upvotes: 0

Ray Toal
Ray Toal

Reputation: 88378

The JavaScript expressions 1%15, 3%15, and 5%15 evaluate to 1, 3, and 5 respectively, as you surmised.

The question you asked seems unrelated to your code post, though, where you are using 15%i and i%3 and so on.

On the other hand, 15%1, 15%3, and 15%5 do all evaluate to zero.

Upvotes: 2

Related Questions