51nod 1256 乘法逆元

 题目链接:

http://www.51nod.com/Challenge/Problem.html#problemId=1256

1256 乘法逆元

给出2个数M和N(M < N),且M与N互质,找出一个数K满足0 < K < N且K * M % N = 1,如果有多个满足条件的,输出最小的。

 收起

输入

输入2个数M, N中间用空格分隔(1 <= M < N <= 10^9)

输出

输出一个数K,满足0 < K < N且K * M % N = 1,如果有多个满足条件的,输出最小的。

输入样例

2 3

输出样例

2

 K*M%N=1

求k的最小整数

扩展欧几里得

已知 x*M + y*N=G(M , N) =1 两边队N取模,即得到  x*M%N =1  所以求扩展欧几里得最小正整数x即可

 

This is the code:

#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<iomanip>
#include<list>
#include<map>
#include<queue>
#include<sstream>
#include<stack>
#include<string>
#include<set>
#include<vector>
using namespace std;
#define PI acos(-1.0)
#define EXP exp(1)
#define pppp cout<<endl;
#define EPS 1e-8
#define LL long long
#define ULL unsigned long long     //1844674407370955161
#define INT_INF 0x3f3f3f3f      //1061109567
#define LL_INF 0x3f3f3f3f3f3f3f3f //4557430888798830399
// ios::sync_with_stdio(false);
// 那么cin, 就不能跟C的 scanf,sscanf, getchar, fgets之类的一起使用了。
const int dr[]={0, 0, -1, 1, -1, -1, 1, 1};
const int dc[]={-1, 1, 0, 0, -1, 1, -1, 1};
inline int read()//输入外挂
{
    int ret=0, flag=0;
    char ch;
    if((ch=getchar())=='-')
        flag=1;
    else if(ch>='0'&&ch<='9')
        ret = ch - '0';
    while((ch=getchar())>='0'&&ch<='9')
        ret=ret*10+(ch-'0');
    return flag ? -ret : ret;
}
LL extended_gcd(LL a,LL b,LL &x,LL &y)
{
    LL ret,temp;
    if(!b)
    {
        x=1;
        y=0;
        return a;
    }
    ret=extended_gcd(b,a%b,x,y);
/*算法
p*a+q*b=GCD(a,b)=GCD(b,a%b)=p*b+q*a%b=p*b+q(a-a/b*b)=q*a+(p-a/b*q)b.
所以使用原数据计算出p-a/b*q=temp储存,
先让x=y,
然后y=temp;
*/
    temp=x-a/b*y;
    x=y;
    y=temp;//都是用变化之前的数据计算
/*一种常用的快速方法
    ret=extended_gcd(b,a%b,y,x);
    y-=a/b*x;
*/
    return ret;//返回最大公约数
}
LL linearequation(LL a,LL b,LL c,LL &x,LL &y)
{
    LL gcd=extended_gcd(a,b,x,y);
    if(c%gcd)
        return 0;
    LL t=b/gcd;
    LL k=c/gcd;
    x*=k;//求解
    y*=k;
    //最小正整数解
    x=(x%t+t)%t;
    if(x==0)
        x+=t;
    return gcd;
}
int main()
{
    LL n,m;
    cin>>m>>n;
    LL x,y;
    linearequation(m,n,1LL,x,y);
    cout<<x<<endl;
    return 0;
}

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值