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.
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.
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
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)