Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properties of the modulo operation

I have the compute the sum S = (a*x + b*y + c) % N. Yes it looks like a quadratic equation but it is not because the x and y have some properties and have to be calculated using some recurrence relations. Because the sum exceeds even the limits of unsigned long long I want to know how could I compute that sum using the properties of the modulo operation, properties that allow the writing of the sum something like that(I say something because I do not remember exactly how are those properties): (a*x)%N + (b*y)%N + c%N, thus avoiding exceeding the limits of unsigned long long.

Thanks in advance for your concern! :)

like image 914
ZLMN Avatar asked Apr 08 '11 13:04

ZLMN


4 Answers

a % N = x means that for some integers 0 <= x < N and m: m * N + x = a.

You can simply deduce then that if a % N = x and b % N = y then

(a + b) % N =
= (m * N + x + l * N + y) % N =
= ((m + l) * N + x + y) % N =
= (x + y) % N =
= (a % N + b % N) % N.

We know that 0 < x + y < 2N, that is why you need to keep remainder calculation. This shows that it is okay to split the summation and calculate the remainders separately and then add them, but don't forget to get the remainder for the sum.

For multiplication:

(a * b) % N =
= ((m * N + x) * (l * N + y)) % N =
= ((m * l + x * l + m * y) * N + x * y) % N =
= (x * y) % N =
= ((a % N) * (b % N)) % N.

Thus you can also do the same with products.

These properties can be simply derived in a more general setting using some abstract algebra (the remainders form a factor ring Z/nZ).

like image 196
bandi Avatar answered Oct 22 '22 23:10

bandi


How about this:

   int x = (7 + 7 + 7) % 10;

   int y = (7 % 10 + 7 % 10 + 7 % 10) % 10;
like image 45
Steve Wellens Avatar answered Oct 22 '22 23:10

Steve Wellens


You can take the idea even further, if needed:

S = ( (a%N)*(x%N)+(b%N)*(y%N)+c%N )%N
like image 34
Martijn Avatar answered Oct 22 '22 23:10

Martijn


You can apply the modulus to each term of the sum as you've suggested; but even so after summing them you must apply the modulus again to get your final result.

like image 34
Dave Costa Avatar answered Oct 23 '22 00:10

Dave Costa