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, ....
Input
Output
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.
分析:
求是否有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;
}
最后
以上就是真实跳跳糖最近收集整理的关于m*a+b=n*c+d的全部内容,更多相关m*a+b=n*c+d内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复