I saw a lot of competitive programmers writing code with ((a + b) % d + d) % d
in C++. Why don't they just use (a + b) % d
? What is that + d
inside parentheses good for? Does it have something to do with negative numbers?
Thanks
Modular arithmetic is the branch of arithmetic mathematics related with the “mod” functionality. Basically, modular arithmetic is related with computation of “mod” of expressions. Expressions may have digits and computational symbols of addition, subtraction, multiplication, division or any other.
The modulo operation is the same as ' the remainder of the division '. If I say a modulo b is c, it means that the remainder when a is divided by b is c. The modulo operation is represented by the '%' operator in most programming languages (including C/C++/Java/Python). So, 5 % 2 = 1, 17 % 5 = 2, 7 % 9 = 7 and so on.
Problems in competitive programming which involve Mathematics are are usually about number theory, or geometry. If you know number theory, that increases your ammo heavily in solving a lot of tougher problems, and helps you in getting a strong hold on a lot of other problems, too.
A familiar use of modular arithmetic is in the 12-hour clock, in which the day is divided into two 12-hour periods. If the time is 7:00 now, then 8 hours later it will be 3:00. Simple addition would result in 7 + 8 = 15, but clocks "wrap around" every 12 hours.
Yes you are correct. Until C++11 the behaviour of the remainder operator %
for negative arguments was left to the implementation, subject to some constraints. And adding d
to the left argument can help that so long as the other terms in that argument sum to greater or equal to -d
, which, in general is not the case. (-a / d
multiples of d
for the case of negative a
would have been a better additive constant in your particular case.)
Yes, it has something to do with negative numbers. It prevents the result from being a negative number under certain conditions. In this case, when the b
variable is negative, the result of b % d
is also negative. This result can never be greater than d
, so adding d
to this result forces the result to be positive.
Below code is Java code, but it has the same principle:
int a = 13;
int b = -23;
int d = 31;
int result1 = (a + b % d + d) % d;
int result2 = (a + b % d) % d;
System.out.println(result1);
System.out.println(result2);
It outputs the following:
21
-10
To avoid integer overflow and to always keep number positive we use modular arithmetic.
Compettitve programmers tend to use (a+b)%b
instead of a%b
when a is a negative number.
a%b = (a+b)%b
(a+b)%b = a%b + b%b = a%b + 0 = a%b
Like a=-2
& b=5
then a%b = 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With