题解 P1082 同余方程

本题出处:NOIP2012Day2T1

题意:求方程\(ax\equiv1\pmod{b}\)的最小正整数解\(x\)

\[ax\equiv1\pmod{b}\]
\[\Rightarrow ax+by=1\]
输入数据保证有解,也就是保证了\(\gcd(a,b)=1\)\(a,b\)互质。
\[\Rightarrow ax+by=gcd(a,b)\]
直接套用扩展欧几里德\((exgcd)\)模板求解即可。注意取模使得\(x\)为最小正整数。

\(code:\)

#include<bits/stdc++.h>
using namespace std;
#define re register
#define ll long long
#define il inline
#define dou double
#define un unsigned
il int read()
{
    char c=getchar();int x=0,f=1;
    while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    return x*f;
}
#define INF 114514114
#define clr(x) memset(x,0,sizeof(x))
int a,b,x,y;
il 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()
{
    a=read();b=read();
    exgcd(a,b,x,y);
    cout<<(x%b+b)%b<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Hakurei-Reimu/p/11518807.html
今日推荐