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.
InputThe 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.
题目大意是:一个怪兽追两个人,如果两个人同时尖叫那么怪兽就会在那个时候把他们抓住。其中一个人在时间b,b+a,b+2a,...时尖叫,另一个人在d,d+c,d+2c,...时尖叫,问你怪兽在什么时候能抓住他们,如果不能抓住则输出-1.
如果满足条件,那么就有:存在两个非负整数x,y使得b+ax=d+cy,也即判断是否存在这样的x,y使得等式成立。
要讨论x,y是否为整数的情况,我们不妨先认定x为整数,通过式子y=(ax+b-d)/c计算出y再判断y是否为整数
令t=b-d代表x=0的情况,每次x+1相当于t+a,令m=t%c,如果m==0,则说明y是整数,那么就输出ax+b也就是t+d
如果m不为0,容易知道余数是呈周期性出现的,比如4,7,10,13,16,19,22,25,28,31对5的余数是4,2,0,3,1,4,2,0,3,1....,所以只要判断得到某一次余数重复出现了,那么m=0的情况就不可能出现,也就可以输出-1
分析到此结束,下面是我的代码。
#include<stdio.h>
#include<string.h>
int main()
{
int a,b,c,m,d,t,i;
int p[105];
/*
相当于存在非负整数x,y使得b+ax=d+cy
即y=(ax+b-d)/c
1<=a,b,c,d<=100
*/
while(scanf("%d%d%d%d",&a,&b,&c,&d)!=EOF)
{
memset(p,0,(c+1)*sizeof(int));
/*p[i]记录余数为i是否出现过
如果余数i已经出现过,那么x继续增加其余数呈周期性变化
说明不存在对应的x使y为整数*/
t=b-d;//当x=0时,判断y是否为整数
while(t<0) t+=a;//最终结果输出t+d,要满足t+d>=d且t+d>=b(恒成立)
m=t%c;
while(p[m]!=1&&m!=0)
{
p[m]=1;//记录余数m出现过
t+=a;//x++
m=t%c;
}
if(m==0) printf("%d\n",t+d);
else printf("-1\n");
}
return 0;
}