51Nod1256 乘法逆元(逆元)

51Nod1256 乘法逆元

Description

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

题解

题意

中文题面

思路

模板,基于扩展欧几里得求乘法逆元,注意模板结合了判断是否存在逆元,如果不存在输出-1

代码

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 0x3f3f3f3f;

#define REP(i,n) for(int i=0;i<(n);i++)

int exgcd(int a,int b,int &x,int &y)
{
    if(b==0){
        x=1;
        y=0;
        return a;
    }
    int r=exgcd(b,a%b,x,y);
    int temp=x;
    x=y;
    y=temp-(a/b)*y;
    return r;
}

int inv(int t,int p){
    int x,y;
    int r = exgcd(t,p,x,y);
    return r == 1?(x%p+p)%p:-1;
}

int main(){
    int N,M;
    while(~scanf("%d %d",&M,&N)){
        printf("%d\n",inv(M,N));
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/caomingpei/p/9558323.html