# Inverse element-application of multiplicative inverse element

1. Problem introduction:
(1) For the problem of m=(a/b)(mod p), since division cannot use the congruence theorem, we need to convert division into multiplication
(a / b)% p = a * inv (b , p) %p =( a%p * inv (b, p )%p) %p
(whereinv (b, p) is the multiplicative inverse of b in the sense of mod p)
Or:
(2) When we The value of (a/b) mod p is required, and a is so large that it will overflow; or b is so large that it will burst accuracy. When the value of a/b cannot be obtained directly, we need to use the multiplicative inverse element.

2. Definition:
If there is ab≡1 (modp), then b is the multiplicative inverse of a in the sense of mod p. Remember b=inv(a) or b=a^-1

3. Properties:
each number a has a unique multiplicative inverse element x corresponding to it, so that ax≡1(mod p), the necessary and sufficient condition for a number to have an inverse element is gcd(a, p)=1, this Time inverse element only exists.
In the sense of modulo p, if a number a has an inverse element x, then dividing by a is equivalent to multiplying by x .

4. Solving the inverse element
Extended Euclid's method:

``````#include<bits/stdc++.h>
using namespace std;

int exgcd(int a,int b,int &x,int &y)
{

if(b==0)
{

x=1,y=0;
return a;
}
int r = exgcd(b,a%b,x,y);
int t = x;
x = y;
y = t - a/b*y;
return r;
}
int inv(int n,int mod)///求n在模mod的情况下的逆元
{

int x,y;
int ans = exgcd(n,mod,x,y);
if(ans == 1)
return (x%mod+mod)%mod;
else
return -1;
}
int main()
{

int n,mod;
cin>>n>>mod;
int ans = inv(n,mod);
if(ans==-1)
cout<<"没有逆元"<<endl;
else
cout<<"逆元为："<<ans<<endl;
return 0;
}

``````

Example
question : hdu1576 question link: http://acm.hdu.edu.cn/showproblem.php?pid=1576

Original question:
(A/B)%9973 is required, but because A is very large, we only give n(n=A%9973) (we give A must be divisible by B, and gcd(B,9973) = 1).

AC code:

``````#include<bits/stdc++.h>
using namespace std;

const int mod=9973;

int exgcd(int a,int b,int &x,int &y)
{

if(b==0)
{

x=1,y=0;
return a;
}
int r = exgcd(b,a%b,x,y);
int t = x;
x = y;
y = t - a/b*y;
return r;
}
int inv(int n,int mod)///求n在模mod的情况下的逆元
{

int x,y;
int ans = exgcd(n,mod,x,y);
if(ans == 1)
return (x%mod+mod)%mod;
else
return -1;
}
int main()
{

int t,b,n;
cin>>t;
while(t--)
{

cin>>n>>b;
int ans=inv(b,mod);
cout<<(n%mod*(ans%mod))%mod<<endl;
}
return 0;
}

``````

### Guess you like

Origin blog.csdn.net/qq_40534166/article/details/99706015
Recommended
Ranking
Daily