Documente Academic
Documente Profesional
Documente Cultură
10^9+7 fulfills both the criteria. It is the first 10-digit prime number and fits
in int data type as well. In fact, any prime number less than 2^30 will be fine
in order to prevent possible overflows.
How modulo is used:
A few distributive properties of modulo are as follows:
( a + b) % c = ( ( a % c ) + ( b % c ) ) % c
( a * b) % c = ( ( a % c ) * ( b % c ) ) % c
( a – b) % c = ( ( a % c ) – ( b % c ) ) % c
(a/b)%c=((a%c)/(b%c))%c
So, modulo is distributive over +, * and – but not over / [Please refer
Modular Division for details]
Method 1:
First, multiply all the number and then take modulo: (a*b*c)
%m = (459405448184212290893339835148809
515332440033400818566717735644307024625348601572) %
1000000007
a*b*c does not fit even in the unsigned long long
int due to which system drop some of its most
significant digits. Therefore, it gives the wrong answer.
(a*b*c)%m = 798848767
But the rules are different for division. To perform division in modulo
arithmetic, we need to first understand the concept of modulo multiplicative
inverse.
Modulo multiplicative Inverse(MMI):
The multiplicative inverse of a number y is z iff (z * y) == 1.
Dividing a number x by another number y is same as multiplying x with the
multiplicative inverse of y.
x / y == x * y^(-1) == x * z (where z is multiplicative inverse of y).
In normal arithmetic, the multiplicative inverse of y is a float value. Ex:
Multiplicative inverse of 7 is 0.142…, of 3 is 0.333… .
In mathematics, modular multiplicative inverse of an integer ‘a’ is an integer
‘x’ such that the product ax is congruent to 1 with respect to the modulus m.
ax = 1( mod m)
The remainder after dividing ax by the integer m is 1.
Example:
If M = 7, the MMI of 4 is 2 as (4 * 2) %7 == 1,
If M = 11, the MMI of 7 is 8 as (7 * 8) % 11 == 1,
If M = 13, the MMI of 7 is 2 as (7 * 2) % 13 == 1.
Observe that the MMI of a number may be different for different M.
So, if we are performing modulo arithmetic in our program and we need the
result of the operation x / y, we should NOT perform
z = (x/y) % M;
Now one question remains.. How to find the MMI of a number n.
There exist two algorithms to find MMI of a number. First is the Extended
Euclidean algorithm and the second using Fermat’s Little Theorem.
You can find both the methods in the given link:
Modular multiplicative inverse
Finding modular multiplicative inverses also has practical applications in the
field of cryptography, i.e. public-key cryptography and the RSA Algorithm. A
benefit for the computer implementation of these applications is that there
exists a very fast algorithm (the extended Euclidean algorithm) that can be
used for the calculation of modular multiplicative inverses.