51Nod 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,如果有多个满足条件的,输出最小的。

Sample Input

2 3

Sample Output

2

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 #include<math.h>
 5 #include<algorithm>
 6 #include<queue>
 7 #include<stack>
 8 #include<deque>
 9 #include<iostream>
10 using namespace std;
11 typedef long long LL;
12 void ex_gcd(LL a,LL b,LL &x,LL &y,LL &d)
13 {
14     if(!b) {x = 1,y = 0,d = a;}
15     else
16     {
17         ex_gcd(b,a%b,y,x,d);
18          y -= x * (a / b);
19     }
20 }
21 LL inv(LL a,LL b)
22 {
23     LL x,y,d;
24     ex_gcd(a,b,x,y,d);
25     return d == 1 ?((x % b) + b)%b : -1;
26 }
27 int main()
28 {
29     LL n,m;
30     int i,p,j;
31     scanf("%lld%lld",&m,&n);
32     printf("%lld
",inv(m,n));
33     return 0;
34 }
View Code
原文地址:https://www.cnblogs.com/daybreaking/p/9351452.html