概述
The Monster
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所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复