Same remainder, Chinese Remainder Theorem

Source: Internet
Author: User

Cool: A between B (mod m), indicating a % m = B % m

The same formula:

Bytes --------------------------------------------------------------------------------------------------------------

 

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

 

China Surplus theorem: solving the same-remainder Equations
N bought a [1] (mod m [1])
N bought a [2] (mod m [2])
......
N bought a [I] (mod m [I])
The equations have the following conditions:M [I]


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

 1  int extend_gcd(int a,int b,int &x,int &y){ 2      if (b==0){ 3          x=1;y=0; 4          return a; 5      } 6      else{ 7          int r=extend_gcd(b,a%b,y,x); 8          y=y-x*(a/b); 9          return r;10      }11  }12  13  int CRT(int a[],int m[],int n)14  {15      int M=1;16      for (int i=1;i<=n;i++) M*=m[i];17      int ret=0;18      for (int i=1;i<=n;i++)19      {20          int x,y;21          int tm=M/m[i];22          extend_gcd(tm,m[i],x,y);23          ret=(ret+tm*x*a[i])%M;24      }25      return (ret+M)%M;26  }27 28  

 

// Reference: http://blog.csdn.net/cyendra/article/details/38402869
There is also an iterative solution to the Chinese Remainder Theorem:
Reference: http://scturtle.is-programmer.com/posts/19363.html

Same remainder, Chinese Remainder 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.