m*a+b=n*c+d

The Monster

 
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 if they will never scream at the same time.


分析:

求是否有m*a+b=n*c+d。

思路1:在1~10^5做标记,m*a+b与n*c+d重合输出否则输出-1.

鉴于上述太没有技术含量有了思路2

思路2:令t=b-d。上式变为m*a+t=n*c→n=(m*a+t)/c。

c的范围已知1~100那(m*a+t)%c至多100种可能,而且一旦产生循环表示不存在整数n。所以循环条件为(m*a+t)%c!=0.


参考代码:

#include<iostream>
#include<cstring>
using namespace std;
bool time[101];

int main()
{
	bool flag = true;
	int a, b;
	int c, d;
	cin >> a >> b;
	cin >> c >> d;
	memset(time, 0, (c + 1) * sizeof(int));
	long long t =  b - d;
	while (t < 0)
	{
		t += a;
	}
	while (!time[t%c] && t%c)
	{
		time[t%c] = 1;
		t += a;
	}
	if (t%c) cout << -1 << endl;
	else
		cout << t + d<<endl;
	return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值