码迷,mamicode.com
首页 > 其他好文 > 详细

POJ_1006_中国剩余

时间:2016-10-09 23:20:56      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

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_中国剩余

标签:

原文地址:http://www.cnblogs.com/zhurb/p/5943993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!