ZOJ 3606 Modular Inverse【乘法逆元】

来源:互联网 发布:mac 返回快捷键 编辑:程序博客网 时间:2024/05/22 01:53

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 ≈ 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),给你a,m,求x,其实也就是求逆元

分析: 根据扩展欧几里得求出后,特判下0的情况,如果为0的话,加一即可

参考代码

#include<bits/stdc++.h>#define ll long longusing namespace std;void egcd(ll a,ll b,ll &d,ll &x,ll &y) {    if(!b) {        d = a;x = 1;y = 0;    } else {        egcd(b,a%b,d,y,x);        y -= x*(a/b);    }}ll inv(ll a,ll m){    ll x,y,d;    egcd(a,m,d,x,y);    return d == 1?(x%m+m)%m:-1;}int main(){    int T;cin>>T;    while (T--) {        ll a,m;cin>>a>>m;        ll res = inv(a,m);        if(res == 0) res++;        if(res == -1) cout<<"Not Exist"<<endl;        else cout<<res<<endl;    }    return 0;}
  • 如有错误或遗漏,请私聊下UP,thx