51Nod 1256 乘法逆元

题目链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1256

给出2个数M和N(M < N),且M与N互质,找出一个数K满足0 < K < N且K * M % N = 1,如果有多个满足条件的,输出最小的。
 
Input
输入2个数M, N中间用空格分隔(1 <= M < N <= 10^9)
Output
输出一个数K,满足0 < K < N且K * M % N = 1,如果有多个满足条件的,输出最小的。
Input示例
2 3
Output示例
2

题解:扩展GCD
 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <cstdio>
 5 #include <vector>
 6 #include <cstdlib>
 7 #include <iomanip>
 8 #include <cmath>
 9 #include <ctime>
10 #include <map>
11 #include <set>
12 #include <queue>
13 using namespace std;
14 #define lowbit(x) (x&(-x))
15 #define max(x,y) (x>y?x:y)
16 #define min(x,y) (x<y?x:y)
17 #define MAX 100000000000000000
18 #define MOD 1000000007
19 #define pi acos(-1.0)
20 #define ei exp(1)
21 #define PI 3.141592653589793238462
22 #define INF 0x3f3f3f3f3f
23 #define mem(a) (memset(a,0,sizeof(a)))
24 typedef long long ll;
25 ll gcd(ll a,ll b){
26     return b?gcd(b,a%b):a;
27 }
28 bool cmp(int x,int y)
29 {
30     return x>y;
31 }
32 const int N=10005;
33 const int mod=1e9+7;
34 /*
35  *  扩展欧几里得法(求ax + by = gcd)
36  */
37 //  返回d = gcd(a, b);和对应于等式ax + by = d中的x、y
38 ll extendGcd(ll a,ll b,ll &x,ll &y)
39 {
40     if (a == 0 && b == 0){
41         return -1; //  无最大公约数
42     }
43     if (b == 0){
44         x = 1;
45         y = 0;
46         return a;
47     }
48     ll d = extendGcd(b, a % b, y, x);
49     y -= a / b * x;
50     return d;
51 }
52 //  求逆元 ax = 1(mod n)
53 ll modReverse(ll a, ll n)
54 {
55     ll x, y;
56     ll d = extendGcd(a, n, x, y);
57     if (d == 1){
58         return (x % n + n) % n;
59     }
60     else{
61         return -1;  //  无逆元
62     }
63 }
64 int main()
65 {
66     ll M, N;
67     while (cin >> M >> N){
68         cout << modReverse(M, N) << endl;
69     }
70     return 0;
71 }
原文地址:https://www.cnblogs.com/shixinzei/p/7290643.html