整理关于 ( m{ax+by=c}),遇到的一系列
在这里,(x) ,(y) 是变量,(a,;b,;c) 是常量
前置:
对于二元一次不定方程 (ax+by=c),有整数解的充要条件是 ((a,b)|c) ;
设 (a=frac a{gcd(a,b)}), (b=frac b{gcd(a,b)}),(c=frac c{gcd(a,b)}),则此时 (gcd(a,b)=1);
若 (gcd(a,b)=1),且不定方程 (ax+by=c) 有整数解 (x=x_0,\,y=y_0) ,则它的一切整数解可表示成:
[x=x_0+bt\y=y_0-at;(tin m Z) ]exgcd可求得 (ax+by=gcd(a,b))的特解,(x_0,\,y_0)
所以 (ax+by=c)的特解可表示成 :
[x_0=x_0cdotfrac{c}{gcd(a,b)}=x_0cdot c\ y_0=y_0cdotfrac{c}{gcd(a,b)}=y_0cdot c ]由 ( m 3)可得 (ax+by=c) 的通解 (x,\,y)
设以下, (ax+by=c) 中,均是 (gcd(a,b)=1)。
1,求 ( m{ax+by=c}), (x)的最小正整数解
设 (x_1) 为 (x) 的最小正整数解,则 (x_1) :
[x_1=(x\%b+b)\%b\
对应;;y_1=frac{c-a*x_1}b
]
2, 求 ( m{ax+by}) 的最大不可解 ( m c),且满足 ( m{x>0,y>0}) : ( m{c=a imes b})
3, 求 ( m{ax+by}) 的最大不可解 ( m c) , 且满足 ( m{xgeq0,ygeq0}) : ( m{c=a imes b-a-b})
2,3的证明见洛谷P3951题解
4,求 ( m{ax+by+cz=k}) 的任意一组解,且满足 ( m{xgeq0,ygeq0,zgeq0}) :
其中:(1leq a,b,cleq10^5 ,0leq kleq 10^{12}) ,保证数据有解
(ax+by=k-cz) 有解的前提是 (gcd(a,b)|(k-cz)),则需枚举z使得满足条件(gcd(a,b)|(k-cz))下,可解的符合的 (x,\,y)。
设 (g=gcd(a,b)) (ec=k\%g),则所求的 (z) 需满足(zc-tg=ec),且 (zgeq0)。
所以求出最小 (z),再枚举满足通项公式的 (z),直到有解。
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=2e5+5;
ll exgcd(ll a,ll b,ll &x,ll &y)
{
if(!b){
x=1;y=0;
return a;
}
ll g=exgcd(b,a%b,x,y);
ll t=x;
x=y;
y=t-a/b*y;
return g;
}
void solve(ll a,ll&b,ll c,ll&x,ll&y)
{
ll g=__gcd(a,b),x0,y0;
a/=g;b/=g;c/=g;
exgcd(a,b,x0,y0);
x0*=c;y0*=c;
x=x0+b;//y=y0-a;
x=(x%abs(b)+abs(b))%abs(b);y=(c-a*x)/b;
}
int main()
{
ll a,b,c,k,g,ec,x,y,z,t,tb,tk,ttb;
scanf("%lld%lld%lld%lld",&a,&b,&c,&k);
g=__gcd(a,b);
ec=k%g;
tb=-g;
solve(c,tb,ec,z,t);
tb=abs(tb);
do{
tk=k-z*c;ttb=b;
solve(a,ttb,tk,x,y);
if(x>=0&&y>=0)
{
printf("%lld %lld %lld
",x,y,z);
break;
}
z+=tb;
}while(1);
}