思路:
=>
然後套exgcd保證X,Y都要>=0.
//#pragma comment(linker, "/STACK:102400000,102400000")
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
typedef long long LL;
#define lson rt<<1, l, mid
#define rson rt<<1|1, mid+1, r
#define mem(a, b) memset(a, b, sizeof(a))
/*
exgcd求不定方程的解
Author: keyboarder_zsq
Time: 2017/10/22 18:53
*/
typedef int Elem;
Elem exgcd(Elem a , Elem b, Elem &x, Elem &y){
if(b == 0){
x = 1, y = 0;
return a;
}
Elem gcd = exgcd(b, a%b, x, y);
Elem temp = x;
x = y;
y = temp - a/b*y;
return gcd;
}
//求方程 a*x + b*y = c 的 x 的最小整數解.
//先利用 exgcd 求 a*x + b*y = gcd(a, b) 的x, y的最小整數解。
//然後再乘上去就好了;
Elem Cal(Elem a, Elem b, Elem c){
Elem x, y, k, t;
Elem gcd = exgcd(a, b, x, y);
if(c%gcd!=0) return -1; //不存在解
x = x * c/gcd; //由a*x + b*y = gcd(a, b) 轉化爲 a*x + b*y = c 的解
k = b/gcd; //約去c後原來b就變爲了b/gcd;
if(k < 0) k = -k; //如果b爲負數就去絕對值
x = (x%k + k) % k; //最小非負整數解
if(x <= 0) x = x + k; //最小正整數解
y = (c - a * x)/b; //如果對y還有要求,先求出y值在進行判斷
while(y<0){
x = x + k;
y = (c - a * x)/b;
}
return x;
}
void solve(){
int a, b, c, d;
cin>>a>>b>>c>>d;
if(b > d){
swap(b, d);
swap(a, c);
}
int tmp;
tmp = Cal(a, -c, d-b);
if(tmp == -1){
puts("-1");
return;
}
printf("%d\n", b+tmp*a);
}
int main(){
solve();
return 0;
}