【算法实践】1.4 编程-Biorhythms(中国剩余定理)

Description
Some people believe that there are three cycles in a person’s life that start the day he or she is born. These three cycles are the physical, emotional, and intellectual cycles, and they have periods of lengths 23, 28, and 33 days, respectively. There is one peak in each period of a cycle. At the peak of a cycle, a person performs at his or her best in the corresponding field (physical, emotional or mental). For example, if it is the mental curve, thought processes will be sharper and concentration will be easier.
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.

在这里插入图片描述
在这里插入图片描述
题意:
人自出生起就有体力,情感和智力三个生理周期,分别为23,28和33天。一个周期内有一天为峰值,在这一天,人在对应的方面(体力,情感或智力)表现最好;

现在给出三个日期,分别对应于体力,情感,智力出现峰值的日期,然后再给出一个起始日期,要求从这一天开始,算出最少再过多少天后三个峰值同时出现;

即找出一个 n n 满足:

  1. ( n + d ) % 23 = p (n+d)\%23=p
  2. ( n + d ) % 28 = e (n+d)\%28=e
  3. ( n + d ) % 33 = i (n+d)\%33=i

这是一道典型的中国剩余定理的题目,原理可以看这位大佬的:中国剩余定理学习笔记

这里写出了一个通用的解法,不只针对 23,28 和 33,改成其他数同样适用:

#include <iostream>

using namespace std;

#define a 23

#define b 28

#define c 33

int main(void)
{
    int j, n1, n2, n3;
    for (j = 1; !((b * c * j) % a == 1); j++)
        ;
    n1 = b * c * j;
    for (j = 1; !((a * c * j) % b == 1); j++)
        ;
    n2 = a * c * j;
    for (j = 1; !((a * b * j) % c == 1); j++)
        ;
    n3 = a * b * j;
    // cout << n1 << ' ' << n2 << ' ' << n3 << endl;
    int p, e, i, d;
    int t = 1;
    while (true)
    {
        cin >> p >> e >> i >> d;
        if (p == -1 && e == -1 && i == -1 && d == -1)
        {
            break;
        }
        int N = a * b * c;
        int n = (n1 * p + n2 * e + n3 * i - d + N) % N;
        if (n == 0)
        {
            n = N;
        }
        cout << "Case " << t++ << ": the next triple peak occurs in " << n << " days." << endl;
    }
    return 0;
}
发布了100 篇原创文章 · 获赞 142 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44936889/article/details/104619684