2

I know what modulus (%) does, it gives you the remainder. But how does it do that? I saw that it uses the formula: modulus = dividend - (dividend / divisor) * divisor 10%3 should give you 1 (10 being the dividend and 3 being the divisor) the forumla gives: 10-(10/3)*3 = 10-10 = 0 which is obviously wrong.

Then again, working with pure variables, dividend - ( dividend / divisor ) * divisor = dividend - dividend = 0

What am I doing wrong here? (Also, the formula is from a native from JASS, the language used in warcraft 3 games)

Billy
  • 21
  • 1
  • 2
  • see also [here](http://stackoverflow.com/questions/6755946/what-is-the-purpose-of-negative-modulus-operator-results/6756109#6756109) – emboss Jul 28 '11 at 11:59
  • You forgot that `(10/3)` truncates toward `0`. The result of this is `3`, not `3.3333333`... So: `10-(10/3)*3 = 10-(3)*3 = 10-9 = 1` – Mooing Duck Mar 15 '12 at 23:14

2 Answers2

4

in the formula (dividend / divisor) is an integer division evaluating to an integer.

So, 10-(10/3)*3 = 10 - 9 = 1

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • Thanks for the quick answer ^^ It was getting frustrating because no matter how many times I put it into the calculator, it gave me 0 xD – Billy Jul 28 '11 at 12:02
2

In many programming languages using C, C++, Java, etc. 10/3 would result in 3 because divisions are actually integer-divisions and the fractional part is truncated.

So, in other words n/d gives you only the quotient.

Now, from arithmetic we know that any positive integer n and any positive integer divider d, n can be represented as: n = q*d + r. If 0 ≤ r < n (and it can be proven that there is only one such positive r that is less than n), q is called the quotient and r is the called the remainder.

In these programming languages, n/d gives you q.

So, n - (n/d)*d = n - q*d = r, the remainder.

Susam Pal
  • 32,765
  • 12
  • 81
  • 103