题目地址:http://codeforces.com/contest/787/problem/A
A. The Monster
time limit per test
memory limit per test
input
output
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.
Input
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).
Output
Print the first time Rick and Morty will scream at the same time, or - 1
Examples
input
20 2 9 19
output
82
input
2 1 16 12
output
-1
Note
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.
【题意】:给出两个等差数列的首项和公差。求两个等差数列的最小的公共值;
【解析】:根据题意。
ax+b=cy+d; (x,y均为任意整数)
移项得:ax-cy=d-b;
根据拓展欧几里得可求得特解x0,根据x的通解公式x=x0+c/gcd
找一个这样的x,使得ax+b>=d;
因为d可能比c大。既然是找最小公共值,就该满足ax+b>=d;
拓展欧几里得用法详见:点击打开链接
【代码】:
#include<stdio.h>
#include<math.h>
typedef long long ll;
ll gcd(ll a,ll b,ll &x,ll &y)
{
if(b==0)
{
x=1;y=0;
return a;
}
ll d=gcd(b,a%b,y,x);
y-=a/b*x;
return d;
}
ll a,b,c,d;
int main()
{
while(~scanf("%lld%lld%lld%lld",&a,&b,&c,&d))
{
ll x,y;
ll dd=gcd(a,c,x,y);
ll t=c/dd;
if((d-b)%dd!=0)
puts("-1");
else
{
x=x*(d-b)/dd;//gcd和d-b是倍数关系
x=(x%t+t)%t;
while(b+x*a<d) x+=t;//d太大
printf("%lld\n",(b+x*a));
}
}
return 0;
}