Description
Since the three cycles have different periods, the peaks of the three cycles generally occur at different times. We would like to determine when a triple peak occurs (the peaks of all three cycles occur in the same day) for any person. For each cycle, you will be given the number of days from the beginning of the current year at which one of its peaks (not necessarily the first) occurs. You will also be given a date expressed as the number of days from the beginning of the current year. You task is to determine the number of days from the given date to the next triple peak. The given date is not counted. For example, if the given date is 10 and the next triple peak occurs on day 12, the answer is 2, not 3. If a triple peak occurs on the given date, you should give the number of days to the next occurrence of a triple peak.
Input
Output
Case 1: the next triple peak occurs in 1234 days.
Use the plural form ``days'' even if the answer is 1.
Sample Input
0 0 0 0
0 0 0 100
5 20 34 325
4 5 6 7
283 102 23 320
203 301 203 40
-1 -1 -1 -1
Sample Output
Case 1: the next triple peak occurs in 21252 days.
Case 2: the next triple peak occurs in 21152 days.
Case 3: the next triple peak occurs in 19575 days.
Case 4: the next triple peak occurs in 16994 days.
Case 5: the next triple peak occurs in 8910 days.
Case 6: the next triple peak occurs in 10789 days.
解题之前,先说一个关于韩信点兵的故事。
传说西汉大将韩信,由于比较年轻,开始他的部下对他不很佩服。有一次阅兵时,韩信要求士兵分三路纵队,结果末尾多2人,改成五路纵队,结果末尾多3人,再改成七路纵队,结果又余下2人,后来下级军官向他报告共有士兵2395人,韩信立即笑笑说不对(因2395除以3余数是1,不是2),由于已经知道士兵总人数在2300到2400之间,所以韩信根据23,128,233,------,每相邻两数的间隔是105,便立即说出实际人数应是2333人(因2333=128+20χ105+105,它除以3余2,除以5余3,除以7余2)。这样使下级军官十分敬佩,这就是韩信点兵的故事。
把上面这个问题简化,就是:已知n%3=2,n%5=3,n%7=5,求n。
再看看我们要解决的题目,输入p,i,e,d四个数,已知(n+d)%23=p, (n+d)%28=e, (n+d)%33=i ,求n。是不是很像?
韩信是怎么解决的呢?
《孙子算经》曾有过这样的题目:有物不知其数,三个一数余二,五个一数余三,七个一数又余二,问该物总数几何?
《孙子算经》中的解法:三三数之,取数七十,与余数二相乘;五五数之,取数二十一,与余数三相乘;七七数之,取数十五,与余数二相乘。将诸乘积相加,然后减去一百零五的倍数。
5乘以7除以3,余2,得5*7*2=70;
3乘以7除以5,余1,得3*7*1=21;
3乘以5除以7,余1,得3*5*1=15。
(70*a+21*b+15*c)就是除3余a,除5余b,除7余c的其中一个解。
这个解可能很大,对3,5,7的最小公倍数取余所得到的就是最小的解。即
(70*a+21*b+15*c)%(3*5*7)
那么韩信点兵问题的最小解就是
(70*2+21*3+15*2)%(3*5*7)=23;
由于士兵人数在2300-2400之间
所以总的士兵人数是22*105+23=2333。
再看我们要解的题目,
33乘以28除以23余8,得33*28*8=5544;
23乘以33除以28余19,得23*33*19=14421;
23乘以28除以33余2,得23*28*2=1288。
(5544×p+14421×e+1288×i)%(23×28×33)=n+d
n=(5544×p+14421×e+1288×i-d)%(23×28×33)
到这里,我们题目基本已经解决了。
需要注意的是,当求得最小值等于0时,需要输出的是下一个周期,也就是23、28、33的最小公倍数21252。
贴几个特殊数据
//24 29 34 0 1
//24 29 34 1 21252
//24 29 34 2 21251
//0 0 0 0 21252
怒贴代码:
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
int p,e,i,d,n;
int count=1;
while(scanf("%d%d%d%d",&p,&e,&i,&d)!=EOF)
{
if(p==-1||e==-1||i==-1||d==-1) break;
n=(21252+5544*p+14421*e+1288*i-d)%(23*28*33);
if(n==0) n=21252;
printf("Case %d: the next triple peak occurs in %d days.\n",count,n);
count++;
}
return 0;
}