乘法逆元(ex_gcd和同余定理)

给出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

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
using namespace std;
typedef long long ll;
ll m,n,k;
void extend_Euclid(ll a,ll b,ll &x,ll &y)
{
    if(b==0)
    {
        x=1;
        y=0;
        return;
    }
    extend_Euclid(b,a%b,x,y);
    int tmp=x;
    x=y;
    y=tmp-(a/b)*y;
}
int main()
{
    int i,j,k;
    ll x,y;
    scanf("%lld%lld",&m,&n);
    extend_Euclid(m,n,x,y);
    while(x<0)
    {
        x+=n;
    }
    printf("%d\n",x);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38984851/article/details/81191497