ZOJ 3609 Modular Inverse(拓展欧几里得求最小逆元)

时间:2023-03-09 08:57:43
ZOJ 3609 Modular Inverse(拓展欧几里得求最小逆元)

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-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
题解:
最小乘法逆元:由ax≡1 (mod m)得:转化为解线性方程ax+by=1
需要注意的地方:最小解取模时不能写成(x%t+t)%t 因为此题要的是正数解 这样写有时会输出0

首先我来回顾下欧几里德的几个定理,有助于理解这道题;

定理一:如果d = gcd(a, b),则必能找到正的或负的整数k和l,使 d = a*x+ b*y。

定理二:若gcd(a, b) = 1,则方程ax ≡ c (mod b)在[0, b-1]上有唯一解。

定理三:若gcd(a, b) = d,则方程ax ≡ c (mod b)在[0, b/d - 1]上有唯一解。

对于ax+by=1;  即ax=1(mod b)      当且仅当gcd(a,b)!=1 的时候,无解!

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <algorithm> #define INF 0x7fffffff
#define EPS 1e-12
#define MOD 1000000007
#define PI 3.141592653579798
#define N 100000 using namespace std; typedef long long LL;
typedef double DB; LL e_gcd(LL a,LL b,LL &x,LL &y)
{
if(b==)
{
x=;
y=;
return a;
}
LL ans=e_gcd(b,a%b,x,y);
LL temp=x;
x=y;
y=temp-a/b*y;
return ans;
} LL cal(LL a,LL b,LL c)
{
LL x,y;
LL gcd=e_gcd(a,b,x,y);
if(c%gcd!=) return -;
x*=c/gcd;
b/=gcd;
if(b<) b=-b;
LL ans=x%b;
if(ans<=) ans+=b;
return ans;
} int main()
{
LL a,b,t;
scanf("%lld",&t);
while(t--)
{
scanf("%lld%lld",&a,&b);
LL ans=cal(a,b,);
if(ans==-) printf("Not Exist\n");
else printf("%lld\n",ans);
}
return ;
}