Modular Arithmetic - Competitive Programming

I have seen many programmers who write code with ((a + b) % d + d) % din C ++. Why don't they just use it (a + b) % d? What is + din parentheses? Is this due to negative numbers?

thank

+4
source share
3 answers

Yes you are right. Prior to C ++ 11, the behavior of the residual operator %for negative arguments was left to implement, subject to some restrictions. And adding dto the left argument can help in that as long as the other members of this argument are summed more or equal -d, which, in general, is not so. ( -a / dmultiples of dnegative awould be the best additive constant in your particular case.)

+8
source

, - . . , b , b % d . d, d .

Java, :

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

:

21
-10
+2

, . Compettitve (a+b)%b a%b, a - .

a%b = (a+b)%b
(a+b)%b = a%b + b%b = a%b + 0 = a%b

a=-2 b=5, a%b = 3

0

Source: https://habr.com/ru/post/1681280/


All Articles