1

I calc -15 mod 18 and here are results:
C: -15 % 18 = -15 (http://codepad.org/DhzkZYHk)
Google: -15 mod 18 = 3 (Type -15 mod 18 into google's search box)

and results of -9 mod 5:
C: -9 % 5 = -4
Google: -9 mod 5 =1

Why these are differents? And how google calculate their mod?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Bình Nguyên
  • 2,252
  • 6
  • 32
  • 47
  • 1
    Because Google is not a C compiler and is not required to follow the same rules as C compilers? – DCoder May 05 '13 at 16:15
  • 1
    possible duplicate of [C,Python - different behaviour of the modulo (%) operation](http://stackoverflow.com/questions/1907565/c-python-different-behaviour-of-the-modulo-operation) – Hasturkun May 05 '13 at 16:18
  • I'll also note [Why does Java's % operator give different results than my calculator for a negative dividend?](http://stackoverflow.com/questions/7479526/why-does-javas-operator-give-different-results-than-my-calculator-for-a-negat?rq=1) which is also relevant. – Hasturkun May 05 '13 at 16:18

2 Answers2

3

Google's calculator does -15 mod 18 as

-15 = 18*(-1) + 3

giving a remainder of 3, whereas C evaluates it as

-15 = 18*(0) - 15

and hence the expression becomes -15.

In general,

a = (a/b)*b + a%b

holds.

Varad
  • 155
  • 1
  • 10
2

Because the % operator in Google is a modulus operator and the % operator in C is a remainder operator.

Modulus and remainder operators differ with respect to negative values. With the modulus operator the sign of the result is the sign of the divisor and with the remainder operator the sign of the result is the sign of the dividend.

ouah
  • 142,963
  • 15
  • 272
  • 331