2

I'm reading a C++ Primer 5th ed and i don't understand why is this true :

The modulus operator is defined so that if m and n are integers and n is nonzero, then (m/n)*n + m%n is equal to m.

I decided to check this and the result was indeed true:

int m = 9;
int n = 2;
if ((m / n)*n + m%n == m)
    std::cout << "true" << std::endl;

1) (m/n)*n == m (9)

2) m%n == 1

3) (m/n)*n + m%n == 10 NOT 9

Can somebody explain what is going on here?

vdublevsky
  • 13
  • 5
  • 3
    `(9/2)*2` does **not** equal `9`. – Oliver Charlesworth Aug 11 '16 at 10:30
  • 1
    Do you understand how integer division works? – taskinoor Aug 11 '16 at 10:31
  • The real culprit of this definition is actually in negative integers.. try -9 ... :) (after you get the idea of integer division first, as answers point out). – Ped7g Aug 11 '16 at 10:31
  • @Ped7g - the definition holds for negative integers too. – Oliver Charlesworth Aug 11 '16 at 10:33
  • @OliverCharlesworth that's the point... which means, that the remainder will be -1, which may be surprising for some people (at least for me it was, before I looked on it better and understood it fully). – Ped7g Aug 11 '16 at 10:35
  • @Ped7g Actually, with 9 and 2, -1 is mathematically correct (too). (But I know you mean that the CPU thinks `(-a % b) == (a % -b) == -(a%b)` which is not always mathematically correct) – deviantfan Aug 11 '16 at 11:32

3 Answers3

2
(m/n)*n == m (9)

You did that calculation wrong. This are integers

9/2 == 4
deviantfan
  • 11,268
  • 3
  • 32
  • 49
0

Run this code to see that you get the expected result.

The reason why you did not verify it manually is this:

(m/n)*n == m (9)

While it is 9 in mathematics, in C++ it is 8. This is because C++ drops fractional part when dividing integers.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Nope, (9/4)*4, for example, is not 9! (It's actually 8)

In C and C++, whenever you're dividing integers, the result is still an integer, so 9/4, for example, is exactly 2 (the fractional part got truncated). And because of this truncation the formula works.

ForceBru
  • 43,482
  • 10
  • 63
  • 98