【NOIP2012提高组】同余方程

https://www.luogu.org/problem/show?pid=1082

方程可化为ax+by=1。

用扩展欧几里得算法得到ax'+by'=gcd(a,b)的一组解后,可得x=x'/gcd(a,b)。

由于x要在[0,b)范围,故最终答案为(x+b)%b。

#include <iostream>
using namespace std;
long long extgcd(long long a, long long b, long long &x, long long &y)
{
    if(!b)
    {
        // ax=a => x=1
        x=1;
        y=0;
        return a;
    }
    else
    {
        long long d=extgcd(b,a%b,x,y);
        long long xx=x,yy=y;
        // now b*xx+(a-q*b)*yy=d  q=a/b
        // a*yy+b*(xx-q*yy)=d
        x=yy;
        y=xx-(a/b)*yy;
        return d;
    }
}
long long a,b;
int main()
{
    cin>>a>>b;
    // ax=1 (mod b) equals to ax+by=1
    // use extgcd(a,b) to get a solution of ax'+by'=gcd(a,b)
    // so x=x'/d
    long long x,y;
    long long d=extgcd(a,b,x,y);
    cout<<(x/d+b)%b<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/ssttkkl/p/7555059.html