exgcd

【题意】

  给定a,b,c,k,必定存在ax+by+cz=k,请求出x,y,z

【题解-解法1】

  因为必定有解,所以枚举c的倍数,然后对 ax + by = k-c*i进行exgcd。

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
typedef long long ll ;
const ll mod = 1e9 + 7 ;
const int N = 1e3 + 10;

ll exgcd( ll a , ll b , ll &x , ll &y ){
    if( b == 0 ){
        x = 1 , y = 0 ;
        return a ;
    }

    ll r = exgcd( b , a % b , y , x );
    y = y - a/b * x ;
    return r ;

}
int main()
{
    ll a , b , c , k ;
    ll x , y , z ;
    scanf("%lld%lld%lld%lld",&a,&b,&c,&k);

    ll Gcd = exgcd( a , b , x , y );

    for( int i = 0 ; i < k / c ; i ++ ){
        if( (k - i * c) % Gcd == 0 ){
            ll tmp = (k - i * c) ;
            exgcd( a , b , x , y );        
            //扩大 ( k - i * c ) / gcd 倍
            x = x * tmp / Gcd ;
            y = y * tmp / Gcd ;

            //计算最小正整数
            x = (x % (b / Gcd) + (b / Gcd)) % (b / Gcd);
            y = (tmp - x * a) / b ;
            z = i ;
            if( x >= 0 && y >= 0 )
                break;

        }
    }
    printf("%lld %lld %lld\n",x,y,z);
    return 0;
}