洛谷 P1082 同余方程 —— exgcd

题目:https://www.luogu.org/problemnew/show/P1082

用 exgcd 即可。

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a,b;
int gcd(int a,int b){return b?gcd(b,a%b):a;}
void exgcd(int a,int b,int &x,int &y)
{
    if(!b){x=1; y=0; return;}
    exgcd(b,a%b,y,x);
    y-=a/b*x;
}
int main()
{
    scanf("%d%d",&a,&b);
    int g=gcd(a,b);
    int x,y; exgcd(a,b,x,y); x=x/g;
    x=(x%b+b)%b;
    printf("%d\n",x);
    return 0;
}

 

posted @ 2018-10-03 08:44  Zinn  阅读(105)  评论(0编辑  收藏  举报