ZOJ - 3609

题目:
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
代码如下:

#include
using namespace std;
typedef long long ll;
ll res;
ll exgcd(ll a,ll b,ll &x,ll &y)
{
    if(!b){
        x = 1,y = 0;
        return a;
    }
    res = exgcd(b,a % b,x,y);
    int temp = x;
    x = y;
    y = temp - a / b * y;
    return res;
}
int main()
{
    ll t,a,b,x,y;
    cin >> t;
    while(t--){
        cin >> a >> b;
        int ans = exgcd(a,b,x,y);
        if(ans != 1) cout << "Not Exist" << endl;
        else{
            x %= b;
            while(x <= 0) x += b;
            cout << x << endl;
        }
    }
    return 0;
}

题意:
已知ax≡1 (mod m). ,知道a和m,让你求x最小的正整数。
思路:
用扩展欧几里得算法,求逆元。和洛谷的一道题很类似,证明前面的博客已写。

你可能感兴趣的:(数论:扩展欧几里得算法)