Modular Inverse(扩展欧几里得)
Posted qq-1585047819
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Modular Inverse(扩展欧几里得)相关的知识,希望对你有一定的参考价值。
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 ≈ 2000 indicating the number of test cases.
Each test case contains two integers 0 < a ≤ 1000 and 0 < m ≤ 1000.
Output
For each test case, output the smallest positive x. If such x doesn‘t exist, output "Not Exist".
Sample Input
3 3 11 4 12 5 13
Sample Output
4 Not Exist 8
1 #include <iostream> 2 #include <cstring> 3 #include <algorithm> 4 #include <map> 5 using namespace std; 6 7 typedef long long ll; 8 9 int t; 10 int a,b,X,Y; 11 12 int gdc(int a,int b) 13 return b==0?a:gdc(b,a%b); 14 15 16 void exgdc(int a,int b,int &X,int &Y) 17 if(b==0) 18 X=1; 19 Y=0; 20 return; 21 22 exgdc(b,a%b,X,Y); 23 int temp=X; 24 X=Y; 25 Y=temp-a/b*Y; 26 27 28 29 int main() 30 ios::sync_with_stdio(false); 31 while(cin>>t) 32 while(t--) 33 cin>>a>>b; 34 int GDC=gdc(a,b); 35 if(1%GDC!=0) cout << "Not Exist" << endl;continue; 36 exgdc(a,b,X,Y); 37 int res=X*(1/GDC); 38 int ans=b/GDC; 39 if(ans<0) ans=-ans; 40 res%=ans; 41 if(res<=0) res+=ans; //题目说的是正数 42 cout << res << endl; 43 44 45 return 0; 46
以上是关于Modular Inverse(扩展欧几里得)的主要内容,如果未能解决你的问题,请参考以下文章