Poj 1006 Chinese Residue Theorem

Source: Internet
Author: User

The Chinese Remainder Theorem comes from a problem in Sun Tzu's computing Sutra:

I don't know the number of things, but the number of three is two, the number of five is three, and the number of seven is two. Ry?

In fact, this question is to solve such a homogeneous equations:

X limit 2 (mod 3)

X forward 3 (mod 5)

X limit 2 (mod 7) solving x

 

As for the solution to this equation, Wikipedia explained in detail:

 

// Reference: http://blog.csdn.net/cyendra/article/details/38402869

For example, poj 1006

As a matter of fact, just draw a picture to understand,

This is the solution to the same equations:

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 }

 

Poj 1006 Chinese Residue Theorem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.