Chinese remainder theorem (Sun Tzu's theorem)

Source: Internet
Author: User

"Chinese remainder theorem" is a famous arithmetic work in the period of 5-6 century in China's northern and Southern dynasties, a "matter unknown number" in the book of grandchildren, a solution to the problem: Today there is no know its number, 33 of the remaining two,

55 of the remaining three, 77 of the remaining two. Asking for geometry? Answer: 23.

According to the above we can get a set of formulas:

X≡2 (mod 3)

x≡3 (mod 5)

X≡2 (mod 7)

That

X% 3 = 2

X% 5 = 3

X% 7 = 2

Then we set X = T1 * A + t2 * b + t3 * C

Continue to set

a≡1 (mod 3) b≡0 (mod 3) c≡0 (mod 3)

A≡0 (mod 5) b≡1 (mod 5) c≡0 (mod 5)

A≡0 (mod 7) b≡0 (mod 7) c≡1 (mod 7)

A = LCM (5,7) * p (a%3=1) b = LCM (3,7) *p (b%5=1) c = LCM (3,5) *p (c%7=1)

= 35 * 2 = 70 = 21 * 1 = 21 = 15 * 1 = 15

Then we can get T1 = 2, t2 = 3, T3 = 2 based on the corresponding color.

So X = 2a + 3b + 2c = 2 * 70 + 3 * 21 + 2 * 15 = 233

233 is a solution to X, the general solution is x = 233 + gcd (3,5,7) *k = 233 + 105*k

These A, B, C (hereinafter referred to as NI) how to ask (Divisor 3, 5, 7 collectively referred to as MI)

X≡y1 (mod M1)

X≡y2 (mod m2)

X≡y3 (mod m3)

...

X≡an (mod mn)

Set x = N1 * y1 + N2 *y2 + N3 * y3 + ... + Nn * yn;

NI can be divisible by M1, M2, M3 、.... 、 mi-1, MI + 1 、... 、 mn, but not divisible by mi and ni%mi = 1

Set ni = LCM (m1, M2, M3, ..., MN)/mi * x = mi * y + 1, requires NI to have X

The above formula can be converted to LCM (M1, M2, M3, ..., MN)/mi * x + (-mi) * y = 1

After the transformation the formula is to expand Euclid, so that you can find the X

Template:

intCRT (intA[],intB[],intN) {//A[i] = divisor, b[i] denotes remainder    intM =1, N, ans =0, x, y;  for(inti =0; I < n; i++) M*= A[i];//because the divisor is 22 coprime, so least common multiple is the product     for(inti =0; I < n; i++) {N= M/A[i]; GCD (N, A[i], x, y);//using the extended Euclidean to find xAns + = N * x *B[i]; }    returnAns%M;}

Chinese remainder theorem (Sun Tzu's 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.