1. What is an inverse element
When solving the formula: (a/b)%m, because b may be too large, there will be an explosion of precision, so it is necessary to change the division to multiplication:
Let c be the inverse of b, then b*c≡1(mod m); ///b*c%m=1%m;
则(a/b)%m = (a/b)*1%m = (a/b)*b*c%m = a*c(mod m);
That is, the modulus of a/b is equal to the modulus of the inverse of a* b ;
This is how the inverse element is applied.
2. The method of finding the inverse element.
(1). Fermat's little theorem
In the case of prime numbers, it has for any integer.
If not divisible, yes.
You can find the inverse of a number when it is a prime number, that is, the inverse.
The data range in the question is 1<=x<=10^9, p=1000000007, p is a prime number;
So x is definitely not divisible by p, so in the end, x^(p-2) is the inverse of x.
But there seems to be a problem? How to judge whether a has an inverse element?
Check the properties of the inverse element to see if the multiplied power value x and a is 1.
When p is relatively large, it is necessary to use fast power to solve
Complexity O(logn);
const int mod = 1000000009 ; long long qpow( long long a, long long b) { if(b<0) return 0; long long res=1; a%=mod; while(b) { if(b & 1) res=(res*a)%mod; b >>= 1; a=(a*a)%mod; } return res; } long long inv( long long a) { return qpow(a,mod-2); }
(2) Extended Euclidean
Given the modulus m, finding the inverse of a is equivalent to solving ax=1(mod m)
This equation can be converted into ax-my=1
and then apply the method of finding a quadratic linear equation, and use the extended Euclidean algorithm to find a set of x0, y0 and gcd
to check whether gcd is 1.
If gcd is not 1, it means that the inverse element is not If it exists
, if it is 1, you can adjust x0 to the range of 0~m-1
PS: This algorithm is more efficient, the constant is small, and the time complexity is O(ln n)
Scalable Euclidean inverse element ax≡1(mod n) where a, n are relatively prime;
ll ecgcd(ll a,ll b,ll &x,ll &y) { if(b==0) { x=1; y=0; return a; } else { ll r=ecgcd(b,a%b,x,y); ll temp=x; x = y; y=y-a/b*temp; return r; } } ll inv(ll a,ll n) { ll x,y; exgcd(a,n,x,y); x = (x%n+n)%n; return x; }
(3) Inverse element playing table method
Sometimes there is such a problem, under the modular prime number p, find the 1~n inverse element n < p (here is an odd prime number). All inverses can be found in O(n). There is a recursion as follows
Its derivation process is as follows, let , then
Divide both sides of the above equation at the same time , and further obtain
Substituting and replacing the sum, we end up with
Initialization , so that all inverses of 1->n modulo odd primes can be found by recursion .
In addition, there is a conclusion that all the inverse element values of the modulus correspond to all the numbers in it, for example , then the corresponding inverse element is .
const int n=le5+5; int inv[n]; void inverse(int n,int p) { inv[1]=1; for(int i=2 ; i<=n ;i++) { inv[i]=(ll)(p-p/i)*inv[p%i]%p; } }