Time Limit: 2000MS | Memory Limit: 65535KB | 64bit IO Format: |
Description
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
Hint
无
Source
浙江2012年省赛J题
(a*x)%m=1 扩展欧几里得求ax+my=1 x>0的最小整数解
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 #define ll __int64 5 6 ll x, y; 7 ll exgcd(ll a, ll b){ 8 if(b == 0){ 9 x = 1; 10 y = 0; 11 return a; 12 } 13 ll d = exgcd(b, a%b); 14 ll t = x; 15 x = y; 16 y = t-a/b*y; 17 return d; 18 } 19 20 int main(){ 21 ll a, b, T; 22 scanf("%I64d",&T); 23 while(T--){ 24 scanf("%I64d%I64d",&a,&b); 25 if(b==1){ 26 printf("1\n"); 27 continue; 28 } 29 //cout<<a<<b<<endl; 30 //ll g = 0; 31 ll g = exgcd(a, b); 32 if(g == 1){ 33 while(x < 0){ 34 x += b; 35 y -= a; 36 } 37 printf("%I64d\n",x); 38 } 39 else 40 printf("Not Exist\n"); 41 } 42 return 0; 43 }
时间: 2024-10-12 22:57:54