Modular Inverse
Time Limit:2000MS MemoryLimit:65536KB 64bitIO Format:%lld& %llu
Description
The modularmodular multiplicative inverse of aninteger a modulo m isan integer x suchthat a-1≡x (mod m). Thisisequivalent toax≡1 (mod m).
Input
There aremultiple test cases. The first line of input isan integer T ≈2000 indicating the number of test cases.
Each test casecontains two integers 0 < a ≤1000 and 0 < m ≤1000.
Output
For each testcase, output the smallest positive x.If such x doesn'texist, output "Not Exist".
Sample Input
3
3 11
4 12
5 13
Sample Output
4
Not Exist
8
References
题目数据不大,可以直接暴力过
训练时候用的扩展欧几里得,在这里顺便回顾一下:
对于求最大公约数有gcd(a,b)=gcd(b,a%b),gcd(a,0)=a;
而扩展欧几里得可以求形如ax+by=gcd(a,b)的方程的解,所以对于ax+by=c;如果c!=gcd(a,b)则无解。
设
ax1+by1=gcd(a,b)
则
bx2+(a%b)y2=gcd(b,a%b)=ax1+by1
即
bx2+(a-a/b)y2=ax1+by1
ax1+by1=ay2+b(x2-a/b*y2)
所以x1=y2 y1=x2-a/b*y2
而b=0时,x=1,y=0
代码实现如下:
void extend_gcd(int a,int b,int&x,int&y)
{
if(b==0)
{
x=1;
y=0;
}
else
{
extend_gcd(b,a%b,x,y);
int temp=x;
x=y;
y=temp-a/b*y;
}
}
对于本题求ax+bm=1
无解情况:m!=1 && gcd(a,m)!=1或者m==1 && a==1
代码如下:
#include<cstdio>
using namespace std;
int T;
int a,m;
int x,y;
int gcd(int a,int b)
{
if (!b)
{
return a;
}
return gcd(b,a%b);
}
void extend_gcd(int a,int b)
{
if(b==0)
{
x=1;
y=0;
}
else
{
extend_gcd(b,a%b);
int temp=x;
x=y;
y=temp-a/b*y;
}
}
int main()
{
scanf("%d",&T);
while (T--)
{
scanf("%d%d",&a,&m);
if (m==1)
{
if (!(a%m))
{
printf("1\n");
}
else
{
if (!(m%a))
{
printf("%d\n",m/a);
}
else
{
printf("Not Exist\n");
}
}
}
else
{
if (gcd(a,m)==1)
{
extend_gcd(a,m);
while (x<0)
{
x+=m;
}
printf("%d\n",x);
}
else
{
printf("Not Exist\n");
}
}
}
return 0;
}