Returns the same result as the remainder of an ax running C (mod m)

Source: Internet
Author: User

 

Convert the form

Ax-c = My

It can be seen that the original formula has a solution when and only when the linear equation ax-My = C has a solution

Set G = gcd (a, m)

Then the number of all shapes, such as ax-my, is a multiple of G.

Therefore, if G does not divide C, the original equation has no solution.

 

Assume that G is divisible by C:

Use the Extended Euclidean algorithm to calculate a special Au + mv = g (U0, V0)

Therefore, an integer c/g can be used to multiply the upper limit.

Au0 * (C/G) + mv0 * (C/G) = C

Obtain the original solution X0 = U0 * (C/g)

 

Number of solutions:

Assume that X1 is another solution of ax sans C (mod m ).

Ax1 ax2 (mod m), so m division ax1-ax2

So (M/G) Division (A/G) (x1-x2)

Because (M/G) and (A/G) mutual quality, so (M/G) Division (x1-x2)

The equation x = x0 + K * (M/G) (k = 0, 1, 2 ,...... G-1)

Total g

 1 void solve(int a, int c, int m) 2 { 3     int u0, v0; 4     int g = ex_gcd(a, m, u0, v0); 5     if(c%g != 0) 6     { 7         printf("The equation has no solution!\n"); 8         return; 9     }10     int i, x;11     for(i=0; i<g; ++i)12     {13         x = c/g*u0 + m/g*i;14         x = x % m;15         if(x<0)16             x+=m;17         printf("%d\n", x);18     }19 }
Code Jun

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.