Issues into
For modulo arithmetic , there are about some properties:
But the only division is not satisfied:
Why divide wrong? Well documented:
For some problems, we must seek in the middle of the process, more than, or too big a number, no less computer memory, the division appears that if this formula, we need to reverse the yuan.
Inverse
definition:
For c, in value is not necessarily equal to the reciprocal of our conventional sense, we can understand the requirement to find a number between 0,1,2 ...... p-1, is multiplied by this number and then a modulo p, obtained as a result.
Now we must return to the previous question, and divided by a number equal to the number multiplied by the inverse of this, in the case of modulo division, is multiplied by the inverse of this number, namely:
This put a division, a multiplication fully converted.
Inverse of nature
Uniqueness
Given a number a, if the inverse mod p c in the presence of, certain unique c.
Reflexivity
c is a reverse yuan, a c is the inverse element.
Solving the inverse yuan
For solving the inverse element, if n is small, it is readily calculated, for example, the inverse element 26 in the mold 3:
But when n is very large, it is very difficult to solve manually.
(1) extended Euclidean algorithm (extend_gcd)
Modulus may not be a prime number, satisfying gcd (a, b) = 1 to
definition:
For the inverse of expression may be doing some rearrangements:
When gcd (a, b) = 1 is substituted into extend_gcd (a, b, x, y), non-negative values of x obtained above is A -1
int extend_gcd(int a, int b, int& x, int& y) { if (b == 0) { x = 1, y = 0; return a; } int q = extend_gcd(b, a % b, x, y); int temp = x; x = y; y = temp - a / b * y; return q; }
(2) Fermat's Little Theorem
This applies only in modulo of a prime number
If p is a prime number, and is not a multiple of p, there are
With both sides divided by a
and so
With a quick look at power requirements, complexity of O (logn)
(3) linear recurrence inverse (magic cookies Act)
This applies only in modulo of a prime number
When there is a prime number p
prove:
Written as a recursive algorithm it is, until 1 because 1 is the inverse 1
int inv(int t, int p) { return t == 1 ? 1 : (p - p / t) * inv(p % t, p) % p; }
这个方法复杂度是O(n),但并不是说比前两个差,它可以在O(n)的复杂度内算出n个数的逆元,上面的算法加一个记忆性搜索就行了
int inv(int t, int p) { return INV[t] = t == 1 ? 1 : (p - p / t) * inv(p % t, p) % p; }