Quality series (1)-mathematical charm (2): Expanding Euclidean Algorithms

Source: Internet
Author: User
Code
///   <Summary>
/// Solve XM + ny = D (D is m, n is the maximum public approx)
///   </Summary>
///   <Param name = "M"> </param>
///   <Param name = "N"> </param>
///   <Param name = "X"> </param>
///   <Param name = "Y"> </param>
///   <Returns> </returns>
Public   Static   Void Oglidextension ( Long M, Long N, Ref   Long X, Ref   Long Y)
{
If (M < N)
{
Oglidextension (n, m, Ref X, Ref Y );
Return ;
}
If (N =   0 )
{
X =   1 ;
Y =   0 ;
Return ;
}

Else
{
Long Q = M % N;
Oglidextension (n, Q, Ref X, Ref Y );
Long Temp = X;
X = Y;
Y = Temp - M / N * Y;
}

}

 

AlgorithmExplanation: (I have no time. I have to go to work now. I will explain it in detail later)

 

Algorithm idea:

 

This is roughly the Euclidean theorem.:

IntegerA, BAndA, BThe maximum number of public approx.Gcd (A, B)

So it must existX, YMakeAx + by = gcd (A, B)

 

Thoughts:Prerequisites,Euclidean Definition

Hypothesis: Ax1 + by1 = gcd (A, B)Founded,IfB = 0SoGcd (a, B) = 0;

In this caseX1 = 1, Y1 = 0You can obtain the correct solution.

IfB! = 0SoGcd (B, A % B) = gcd (B, a-a/B * B)

According to our assumptionsBx2 + (a-a/B * B) y2 = gcd (B, a-a/B * B)

ThereforeAx1 + by1 = bx2 + (a-a/B * B) y2 = ay2 + (x2-a/by2) B

ThereforeX1 = Y2, Y1 = x2-A/by2

While,For anyA, BIfB! = 0Perform the following iteration:A = B, B = A % B

EventuallyB = 0

Then we can carry out iterative solutions based on the above theorem.

A

B

A/B

R

X = 1

Y = 0

15

9

1

6

1

0

9

6

1

3

0

-1

6

3

2

0

-1

2

3

0

End

End

ENE

End

 

 

 

 

 

 

 

 

 

 

 

 

 

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.