Poj 2891 modulus linear equations (mi mj non-reciprocal)

Source: Internet
Author: User
Tags modulus

Question:

X = AI (mod mi) 1 <= I <= K

Consider K = 2 first:

X = A1 (mod M1)

X = a2 (mod m2)

D | (a1-a2), where D = (M1, M2)

The proof is as follows:

Necessity: Let X be the solution of the above homogeneous equations, so there is an integer Q1, Q2 makes X = A1 + m1 * Q1, x = a2 + m2 * Q2, remove X and get a1-a2 = m2q2-m1q1. Because d = (M1, M2), d | (a1-a2 ).

Adequacy: If D = (M1, M2) | (a1-a2) is true, then m1 * x + m2 * Y = a1-a2 has a solution.

Set to x0 and Y0. So m2 * Y0 = a1-a2 (mod M1)

Note X1 = a2 + m2 * y0, you can know X1 = a2 (mod m2), and X1 = a2 + m2 * Y0 = a2 + (a1-a2) = A1 (mod M1)

So X1 = a2 (mod m2) = A1 (mod M1)

So X = x1 (mod [M1, M2])

In addition, if both X1 and X2 are solutions of the same equations above, X1 = x2 (mod M1), X1 = x2 (mod m2 ), from the same remainder, X1 = x2 (mod [M1, M2]) is obtained. That is, the interpretation of the modulus [M1, M2] and the same remainder equations is unique.

Pass.

····

K> 2. .

# Include <cstdio> # define lint _ int64lint egcd (lint A, lint B, lint & X, lint & Y) {lint TMP, RET; If (B = 0) {x = 1, y = 0; return a;} ret = egcd (B, A % B, x, y); TMP = x, x = Y, y = TMP-A/B * Y; return ret;} lint gcd (lint A, lint B) {If (B = 0) return a; return gcd (B, A % B);} // obtain the modulus linear equations Ax = B (mod m) lint modular_linear (lint A, lint B, lint m) {lint D, X, Y; D = egcd (a, m, X, Y); If (B % d! = 0) Return-1; // if no solution is available, return-1. Return (x * (B/d) % m + M) % m;} int main () {lint A1, A2, M1, M2, K, Y; while (scanf ("% i64d", & K )! = EOF) {bool flag = false; scanf ("% i64d % i64d", & M1, & A1); If (k = 1) y = A1; for (INT I = 1; I <K; I ++) {scanf ("% i64d % i64d", & m2, & A2); If (FLAG) continue; lint y = modular_linear (M2, A1-A2, M1); If (y =-1) {flag = true; continue;} a1 = a2 + m2 * Y; m1 = m1 * m2/gcd (M1, M2); a1 = (a1% M1 + M1) % M1;} If (FLAG) printf ("-1 \ n "); else printf ("% i64d \ n", A1);} return 0 ;}

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.