J - Modular Inverse ZOJ - 3609

The modular modular multiplicative inverse of an integer a modulo m is an integer x such that a-1x (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

References

#include<bits/stdc++.h>

using namespace std;
typedef long long ll;
/*
真的太阴了,还是自己的惯性,太强,包括自己对于逆元不是很熟
所以导致直接就是很蒙
竟然1的时候,可以两边同时mod,服了 
*/

int main()
{
	ios::sync_with_stdio(false);
	int T;
	cin>>T;
	while(T--){
		ll a,m,ans;
		cin>>a>>m;
		int flag=0;
		for(ll i=1;i<=m;i++){
			if((a*i)%m==1%m){
				flag=1;
				ans=i;
				break;
			}
		}
		if(flag)
			cout<<ans<<endl;
		else 
			cout<<"Not Exist"<<endl;
	}
	return 0;
}

#include<bits/stdc++.h>

using namespace std;
typedef long long ll;

ll exgcd(ll a,ll b,ll& d,ll& x,ll&y){
	if(!b){  
        d=a;x=1;y=0;  
    }  
    else{  
    	exgcd(b,a%b,d,y,x);  
        y-=x*(a/b);  
    } 
}
/*
要是开这个关流的,就不要用scanf了,要不然会wa 
*/

int main()
{
	ios::sync_with_stdio(false);
	int T;
	cin>>T; 
	while(T--){
		ll a,m;
		cin>>a>>m;
		if(m==1){
			cout<<"1"<<endl;
			continue;
		}
		ll x,y,gcd;
		exgcd(a,m,gcd,x,y);
		if(gcd!=1){
			cout<<"Not Exist"<<endl;
			continue;
		}
		if(x<=0){
			x=(x%m+m)%m;
		}
		cout<<x<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36424540/article/details/80041239