A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.
The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).
The second line contains two integers c and d (1 ≤ c, d ≤ 100).
Print the first time Rick and Morty will scream at the same time, or - 1 if they will never scream at the same time.
20 2 9 19
82
2 1 16 12
-1
In the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82.
In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.
直接套个扩欧的板子,嗯需要注意的就是,求出x最小正整数解来之后,y的值不一定是正整数,这时候要确保y也是正整数。
由于移项之后变成ax-cy=d-b;也就是ax+c(-y)=d-b;所以我们求出来的y应当大于等于0,那么-y就应当小于0了。当-y大于0的时候我们增加x这样下去自然就可以得到正整数的y了。
#include <bits/stdc++.h>
using namespace std;
const int MAXN=520;
const int inf=1e9;
void exgcd(int a,int b,int &g,int &x,int &y)
{
if(!b)
{
x=1;
y=0;
g=a;
}
else
{
exgcd(b,a%b,g,y,x);
y-=a/b*x;
}
}
int main()
{
int a,c1,b,c2;
scanf("%d%d%d%d",&a,&c1,&b,&c2);
int c=c2-c1;
int g,x,y;
exgcd(a,b,g,x,y);
if(c%g)puts("-1");
else
{
int b1=b/g;
x*=(c/g);
x=(x%b1+b1)%b1;
while((c-a*x)/b>0)x+=b1;
printf("%d\n",a*x+c1);
}
return 0;
}
看不懂扩欧的看博客 数论->扩欧