2

Why is the following true?

print(-7 % 6 == 5);

This means that -7 % 6 yields 5, but I would expect to see -1 (in JavaScript this is the case).

Proof in DartPad.

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402

2 Answers2

3

The modulo behavior in Dart is different from the behavior in JavaScript, C, C++, and others. It shares its behavior with Python and about this topic there is a question with great answers here.

Modulo will always yield a positive number in Dart.


Adding a bit to the superb answer by @kennytm, the intuitive explanation for this is that it works analogous to positive factorisation (at least in Dart):

17 % 6 == 5          <=> -7 % 6 == 5
(2 * 6 + 5) % 6 == 5 <=> (-2 * 6 + 5) % 6 == 5

However, it could have easily been implemented differently, reasonably, but this is how it works in Dart.

A benefit of this is the following (quote from the answer mentioned earlier):

It is chosen over the C behavior because a nonnegative result is often more useful. An example is to compute week days. If today is Tuesday (day #2), what is the week day N days before? In Python we can compute with

return (2 - N) % 7
Community
  • 1
  • 1
creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
1

The % is actually a remainder operator in Java. So it would return -1.

But a true modulo operator can have many remainders. This is because
a modulo operator means.

if b mod(m) == c Then there exists some integer k where km = (b - c)
which means that

(1) c = b - km for any integer k is a valid answer.

so in your example, -7 % 6 = 5 works because k6 = (-7 -5) = -12 so k = -2.

by (1) above, c = -7 - k6 are all valid answers.

So for -3 <= k <= 3

11, 5, -1, -7, -13, -19, -25 are all valid `

To get the expected answer from your perspective, simply subtract
the modulus from the actual answer. So 5 - 6 = -1

WJS
  • 36,363
  • 4
  • 24
  • 39