P1082 同余方程

题目描述

给定\(a,b\),求最小的正整数\(x\)满足\(a \cdot x\equiv 1 \pmod{b}\)\(a,b \le 2 \times 10^9\)

简单口胡

\(ax \equiv b \pmod{m}\) 可变形为\(ax + my = b\)求解,求到一个解\(x_0\),其通解即为与\(x_0\)\(\dfrac{m}{\gcd{a,m}}\)同余的所有整数。

将原式变形为解\(ax + by = 1\),求出来的\(x\)\(b\)取膜,即为最小正整数解

# include <bits/stdc++.h>
using namespace std;

# define int long long

int a,b;
int x,y;

int gcd(int x,int y)
{
    if(x % y == 0) return y;
    else return gcd(y,x % y);
}

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

signed main(void)
{
    scanf("%lld%lld",&a,&b);
    //solve ax + by = 1
    int d = exgcd(a,b,x,y);
    int x0;
    if(x > 0) x0 = x % b;
    else x0 = (x + b * (abs(x) / b + 1)) % b;
    printf("%lld\n",x0);
    return 0;
}
posted @ 2021-04-19 22:18  luyiming123  阅读(51)  评论(0编辑  收藏  举报