-4

This is true according to Straustrup in PPP, page 68.

Using algebra I can reduce it to

   a/b * b + a%b == a
     a     + a%b == a,  // b in numerator and denominator cancel each other

But that still doesn't explain the proof.

Cœur
  • 37,241
  • 25
  • 195
  • 267
etonw
  • 9
  • 2

2 Answers2

2

For each two integers a and b you have equation

a = n * b + r;

where n is how many times a is divisible by b and r is a remainder.

For example if a is equal to 25 and b is equal to 6 then you can write

a = 4 * 6 + 1
    n   b   r

Using operators of C++ you can write the same like

a = a / b * b + a % b
      n           r
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

You omitted the fact that a and b are integers.

Operator / with two integers will perform whole number division and discard remainder. The remainder can be calculated with operator %. In other words expression a/b says how many times b can fit in a as a whole. And a%b what would be left in a after performing that operation. The result of expressiona - (a % b) would leave no remainder being divided by b. So (a / b) * b is equal to a - (a % b) which gives us following expression (a / b) * b == a - (a % b)

Teivaz
  • 5,462
  • 4
  • 37
  • 75
  • Thank your your time @teivaz ! I have decided to write a program and test the results to figure out this integer division rules – etonw Jun 20 '17 at 21:10
  • @etonw It's generally better to understand the theory first and test second. Relying on observed behavior can leave you with misconceptions. Worst, in c++, you may eventually be observing undefined behavior which can wreck havoc on your sanity and lead you to believe all sorts of incorrect things. Please carefully read this answer, it's accurate and simple. – François Andrieux Jun 21 '17 at 13:13
  • Thank you @FrançoisAndrieux – etonw Jun 22 '17 at 13:55