题目
生物周期,三种属性的生物周期为23,28,和33天。已知每个周期出现的某个日期,现在是第d天,问第多少天三种周期同时到达。
分析
数论,中国剩余定理。用扩展的欧几里得求逆元。
说明
经典例题。。。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void exgcd(int a, int b, int &r, int &x, int &y)
{
if (!b) {
r = a;
x = 1;
y = 0;
}else {
exgcd(b, a%b, r, y, x);
y -= a / b * x;
}
}
int main()
{
int d, Mi, ti, y, k, cases = 1;
int r[3], m[3] = {23, 28, 33};
while (~scanf("%d%d%d%d", &r[0], &r[1], &r[2], &d) && d != -1) {
int M = m[0] * m[1] * m[2], flag = 1, ans = 0;
for (int i = 0; i < 3; ++ i) {
Mi = M/m[i];
exgcd(Mi, m[i], k, ti, y);
if (ti < m[i])
ti += m[i];
ans = (ans + Mi * ti * r[i]) % M;
}
while (ans <= d) {
ans += M;
}
ans -= d;
printf("Case %d: the next triple peak occurs in %d days.\n", cases ++, ans);
}
return 0;
}