Pentium.Labs

System全家桶:https://zhuanlan.zhihu.com/c_1238468913098731520

导航

poj 1006 中国剩余定理解同余方程

 

其实画个图就明白了,

该问题就是求同余方程组的解:

n+d≡p (mod 23)

n+d≡e (mod 28)

n+d≡i (mod 33)

 

 1 #include "iostream"
 2 using namespace std;
 3 int a[5],m[5];
 4 int p,e,i,d,ans;
 5 
 6 int extend_gcd(int a,int b,int &x,int &y){
 7     if (b==0){
 8         x=1;y=0;
 9         return a;
10     }
11     else{
12         int r=extend_gcd(b,a%b,y,x);
13         y=y-x*(a/b);
14         return r;
15     }
16 }
17 
18 int CRT(int a[],int m[],int n)
19 {
20     int M=1;
21     for (int i=1;i<=n;i++) M*=m[i];
22     int ret=0;
23     for (int i=1;i<=n;i++)
24     {
25         int x,y;
26         int tm=M/m[i];
27         extend_gcd(tm,m[i],x,y);
28         ret=(ret+tm*x*a[i])%M;
29     }
30     return (ret+M)%M;
31 }
32 
33 int main()
34 {
35     int T=0;
36     while (cin>>p>>e>>i>>d)
37     {
38         T++;
39         if ((p==-1)&&(e==-1)&&(i==-1)&&(d==-1))
40             break;
41         a[1]=p;     a[2]=e;     a[3]=i;
42         m[1]=23;    m[2]=28;    m[3]=33;
43         ans=CRT(a,m,3);
44         ans=ans-d;
45         if (ans<0)  ans+=21252;
46         ans=ans%21252;
47         if (ans==0)     ans=21252;
48         //Case 1: the next triple peak occurs in 1234 days.
49         cout<<"Case "<<T<<": the next triple peak occurs in "<<ans<<" days."<<endl;
50     }
51     return 0;
52 }

 

posted on 2014-11-01 11:52  Pentium.Labs  阅读(303)  评论(0编辑  收藏  举报



Pentium.Lab Since 1998