EXgcd学习笔记

由于公式不熟练,就只好把手写笔记传上来了
4c0f7dfa04f87a9330abd5c03d61fc6f
e0e8b61c2f70d9bc9f0ca2bdd367398c
另外给出模板题参考代码二元一次不定方程 (exgcd)

#include<bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#define dbg(x) cerr<<#x<<':'<<x<<'\n'
#else
#define dbg(x) 
#endif
#define all(x) (x).begin(),(x).end()

#define int long long
using ll=long long;
#define db double
#define vi vector<int> 
#define pb push_back 
#define pii pair<int,int>
#define fi first
#define se second
#define endl '\n'
const ll INF=0x3f3f3f3f3f3f3f3f;
const int N=2e5+5,MOD=998244353;

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

int floord(int x,int y){
    int res=x/y;
    if(x%y<0)  res--;
    return res;
}
int ceild(int x,int y){
    int res=x/y;
    if(x%y>0) res++;
    return res;
}

void solve(){
    int a,b,c;
    cin>>a>>b>>c;
    if(c%gcd(a,b)){
        cout<<"-1\n";
        return ;
    }
    int x0,y0,xmn=INF,xmx=-INF,ymn=INF,ymx=-INF,ub,lb,dx,dy;
    int g=gcd(a,b);
    dx=b/g,dy=a/g;
    exgcd(a,b,x0,y0);
    int x1=c/g*x0,y1=c/g*y0;
    lb=ceild(1-x1,dx),ub=floord(y1-1,dy);
    xmn=x1+lb*dx;
    ymn=y1-ub*dy;
    xmx=x1+ub*dx;
    ymx=y1-lb*dy;
    int cnt=ub-lb+1;
    if(cnt>0){
        cout<<cnt<<' '<<xmn<<' '<<ymn<<' '<<xmx<<' '<<ymx<<endl;
    }else{
        cout<<xmn<<' '<<ymn<<endl;
    }
}

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int T=1;
    cin>>T;
    while(T--)
        solve();
    return 0;
}
posted @ 2026-08-24 17:02  江蝶  阅读(1)  评论(0)    收藏  举报