POJ_1006_中国剩余

Posted 冷暖知不知

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ_1006_中国剩余相关的知识,希望对你有一定的参考价值。

http://poj.org/problem?id=1006

 

中国剩余定理用来解求模方程组,用到了逆元。

这题三个数互质,直接用扩展欧几里德可得逆元。

 

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;

int a[5],m[5],n,d;

void e_gcd(int a,int b,int &x,int &y)
{
    if(!b)
    {
        x = 1;
        y = 0;
        return;
    }
    e_gcd(b,a%b,x,y);
    int temp = x;
    x = y;
    y = temp-a/b*y;
}

int CRT()
{
    int M = 1,ans = 0;
    for(int i = 1;i <= n;i++)   M *= m[i];
    for(int i = 1;i <= n;i++)
    {
        int x,y,Mi = M/m[i];
        e_gcd(Mi,m[i],x,y);
        ans = (ans+Mi*x*a[i])%M;
    }
    if(ans < 0) ans += M;
    return ans;
}

int main()
{
    n = 3;
    m[1] = 23;
    m[2] = 28;
    m[3] = 33;
    int cnt = 1;
    while(scanf("%d%d%d%d",&a[1],&a[2],&a[3],&d))
    {
        if(a[1] == -1 && a[2] == -1 && a[3] == -1 && d == -1)   break;
        int ans = CRT();
        if(ans <= d)    ans += 21252;
        ans -= d;
        printf("Case %d: the next triple peak occurs in %d days.\n",cnt++,ans);
    }
    return 0;
}

 

以上是关于POJ_1006_中国剩余的主要内容,如果未能解决你的问题,请参考以下文章

[Poj1006]生理周期 (中国剩余定理)

poj1006-biorhythms中国剩余定理

中国剩余定理

中国剩余定理算法详解 + POJ 1006 Biorhythms 生理周期

中国剩余定理 poj1006 模板

poj 1006Biorhythms(数论--中国剩余定理 模版题){附中国剩余定理 }