输入2个数M, N中间用空格分隔(1 <= M < N <= 10^9)
输出一个数K,满足0 < K < N且K * M % N = 1,如果有多个满足条件的,输出最小的。
2 3
2
K*M%N=1就相同与K*M = N*Y+1,也可以相当于K*M+N*Y=1,所以K = (x+n)%n;
1 #include <iostream> 2 #include <stdio.h> 3 using namespace std; 4 5 int extgcd(int a, int b, int &x, int &y){ 6 int d = a; 7 if(b != 0){ 8 d = extgcd(b,a%b,y,x); 9 y -= (a/b)*x; 10 }else{ 11 x = 1; y = 0; 12 } 13 return d; 14 } 15 int mod(int a, int m){ 16 int x, y; 17 extgcd(a,m,x,y); 18 // cout << x << ‘ ‘ << y << endl; 19 return (m+x)%m; 20 } 21 int main(){ 22 int n, m; 23 scanf("%d%d",&m,&n); 24 printf("%d\n",mod(m,n)); 25 return 0; 26 }
原文:http://www.cnblogs.com/xingkongyihao/p/7222898.html