ZOJ Problem Set - 3609
Modular Inverse
Time Limit: 2 Seconds
Memory Limit: 65536 KB
The modular modular multiplicative inverse of an integer a modulo m is an integer x such that a-1≡x (mod m)
. This is equivalent to ax≡1 (mod m)
.
Input
There are multiple test cases. The first line of input is an integer T
Each test case contains two integers 0 < a ≤ 1000 and 0 < m
Output
For each test case, output the smallest positive x. If such x
Sample Input
3
3 11
4 12
5 13
Sample Output
4 Not Exist 8
//题意:
给出a,m的值,让你找出一个x使得(a*x)%m==1成立。
拓展欧几里德变形
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define ll long long
using namespace std;
int gcd(int a,int b,int &x,int &y)
{
if(!b)
{
x=1;
y=0;
return a;
}
int ans=gcd(b,a%b,x,y);
int tmp=x;
x=y;
y=tmp-a/b*y;
return ans;
}
int cal(int a,int b,int c)
{
int x,y,cnt;
int d=gcd(a,b,x,y);
if(c%d!=0)
return -1;
x*=c/d;
b/=d;
if(b<0)
b-=b;
cnt=x%b;
if(cnt<=0)
cnt+=b;
return cnt;
}
int main()
{
int t,num;
int a,b,c,x,y;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&a,&b);
num=cal(a,b,1);
if(num==-1)
printf("Not Exist\n");
else
printf("%d\n",num);
}
return 0;
}