Euclidean Algorithm (c)

Source: Internet
Author: User

Grand Prix
# Include <stdio. h>
Void luwei_gcd (int a, int B, int & d, int & x, int & y)
{
If (B = 0) // for ax + by = d and B = 0, there is obviously x = 1 (because gcd (a, B) = d, a = d)
{
D =;
X = 1;
Y = 0;
Return;
}
Luwei_gcd (B, a % B, d, y, x); // a * x + B * y = d can be converted to B * y + (a % B) * (y-x * (a/B) = d
Y-= x * (a/B); // when backtracking x = y, y = y-x * (a/B), update the values of x and y.
}
// Ax limit 1 (mod n) satisfies gcd (a, n) = 1. This problem can be converted to ax + bn = 1. Then, the above function can be used to obtain x
Int shuchu (int a, int n)
{
Int d, x, y;
Luwei_gcd (a, n, d, x, y );
If (d = 1) // ax + bn = 1
{
X = x % n;
If (x <0)
Return (x + n) % n; // The returned value must be a positive number.
Printf ("the reverse element of a mod B is: % dn", x );
Printf ("B mod a's reverse element: % dn", (1-a * (x-26)/n );
}
Else
Printf ("a and B are not mutually exclusive, and there is no reverse element n ");
}

Int main ()
{
Int a, B;
Printf ("enter two positive integers: (a <B) n ");
Scanf ("% d", & a, & B );
Shuchu (a, B );
Return 0;
}

Related Article

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.