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, ....
![](http://codeforces.com/predownloaded/ba/58/ba58e8e7c79422be337c551c72c11c1b60763948.png)
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
#include <iostream>
using namespace std;
int main()
{
int a,b,c,d;
int i,j,k,flag=0;
while (scanf("%d%d%d%d",&a,&b,&c,&d)!=EOF)
{
for (i=b;i<=b+110*a;i+=a)
for (j=d;j<=d+110*c;j+=c)
{
if (i==j)
{
flag=1;
cout<<i<<endl;
break;
}
if (flag)
break;
}
if (!flag)
cout<<"-1"<<endl;
flag=0;
}
return 0;
}
#include<iostream>
using namespace std;
int exgcd(int a,int b,int &x,int &y)
{
int r,temp;
if (b==0)
{
x=1;
y=0;
return a;
}
r=exgcd(b,a%b,x,y);
temp=x;
x=y;
y=temp-a/b*y;
return r;
}
int main ()
{
int a,b,c,d,q;
int x,y,min;
while (scanf ("%d%d%d%d",&a,&b,&c,&d)!=EOF)
{
q=d-b;
min=exgcd(a,c,x,y);
if (q%min!=0)
cout<<"-1"<<endl;
else
{
x=x*(q/min);
x=(x%(c/min)+(c/min))%(c/min);
y=(b-d+x*a)/c;
while (y<0)
{
x=x+c/min;
y=(b-d+x*a)/c;
}
printf("%d\n",b+a*x);
}
}
return 0;
}