-1

Just doing some basic modulo operations and trying to wrap my head around the below operations with questions marks.

0%5 // 0 - Totally understand
1%5 // 1 ?
2%5 // 2 ?
3%5 // 3 ?
4%5 // 4 ?
5%5 // 0 - Totally understand

Perhaps I'm thinking in the wrong way. For example 1/5 would return a Double of 0.2 and not a single integer so how does it return a remainder of 1?

I understand these. It makes sense but the above I can't wrap my head around.

9%4   // 1
10%2  // 0
10%6  // 4

Be great if someone could explain this. Seems I'm having a brain fart. Source of learning.

Samuel
  • 5,529
  • 5
  • 25
  • 39
  • What's wrong with module. `1 = 5 * 0 + 1`. Actually 1/5 will return 0, not 0.2. Because of 1 and 5 is `Int` type – Quoc Nguyen Sep 21 '18 at 08:52
  • 2
    Note that `%` is the *remainder operator,* not *modulo.* Compare [Negative number modulo in swift](https://stackoverflow.com/q/41180292/1187415). – Martin R Sep 21 '18 at 08:55
  • 1%5 can fit no complete 5's, so the remainder is one. Hence 2 % 5 can fit no complete 5's and the remainder is 2. – stevenpcurtis Sep 21 '18 at 09:14

2 Answers2

1

From the same Basic Operators page that you link to:

The remainder operator (a % b) works out how many multiples of b will fit inside a and returns the value that is left over (known as the remainder).

Specifically for 1 % 5:

5 doesn't fit in 1, so it fits 0 times.

This means that 1 can be described as

1 = (5 * multiplier) + remainder

Since the multiplier is 0, the remainder is 1

1 = (5 * 0) + remainder
1 = remainder

If we instead look at 6 % 5 the remainder is also 1. This is because 5 fit in 6 one time:

6 = (5 * multiplier) + remainder
6 = (5 * 1) + remainder
6-5 = remainder
1 = remainder
David Rönnqvist
  • 56,267
  • 18
  • 167
  • 205
0

This / the division operator when you say 1/5 if division is in integer it'll give 0 , but this 1.0/0.5 when you make it in Double , it'll give 0.2

but % the modulo operator when you say 1%5 = 1 because you have 1 = 0*5 + 1 which means that 1 has zero number of 5 and the reminder is 1

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87