Poj 2115 modulus linear equation Ax = B (mod N)

Source: Internet
Author: User
Tags modulus
/* (X * C + a) % (2 ^ K) = B → (x * C) % (2 ^ K) = B-A satisfies the theorem: inference 1: The equation Ax = B (mod n) has a solution for the unknown x. if and only when gcd (A, n) | B. Inference 2: The equation Ax = B (mod n) or there are d different solutions to the modulus n, where D = gcd (A, n), or no solution. Theorem 1: Set d = gcd (A, n). Assume that the integers x and y meet d = AX + by (for example, a group of solutions obtained by the extended Euclid algorithm ). If d | B, then the equation Ax = B (mod n) has a solution where x0 satisfies X0 = x * (B/d) mod n. In particular, let's set E = x0 + N, the minimum integer solution of the equation Ax = B (mod n) x1 = e Mod (N/d ), the maximum integer is x 2 = X1 + (D-1) * (N/d ). Theorem 2: assume that the equation Ax = B (mod n) has a solution, and x0 is any solution of the equation, then the equation has exactly d different solutions for model N (D = gcd (A, n), namely: xi = x0 + I * (N/d) mod n. */# Include <stdio. h >__ int64 ext_gcd (_ int64 A ,__ int64 B ,__ int64 & X ,__ int64 & Y) {If (B = 0) {x = 1; y = 0; return a;} _ int64 d = ext_gcd (B, A % B, x, y); _ int64 T = x; X = y; y = T-A/B * Y; return D ;}__ int64 modular_linear (_ int64 A ,__ int64 B ,__ int64 N) {_ int64 D, E, x, Y; D = ext_gcd (A, n, x, y); If (B % d) return-1; E = x * (B/d) % N + N; Return e % (n/d);} int main (void) {_ int64 D, a, B, c, K; while (scanf ("% LLD", & A, & B, & C, & K), a | B | c | K) {d = modular_linear (C, B-A, (_ int64) 1 <k); If (D =-1) puts ("forever "); else printf ("% LLD \ n", d);} 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.