Use of Euclidean Algorithms

Source: Internet
Author: User

The euclidean algorithm, called the moving phase division, is used to calculate the public factor of known natural numbers m and n. Use the program to explain the specific situation of separation.

First, let's look at Recursive Implementation:

Copy codeThe Code is as follows: int getcd (int m, int n)
{
If (m <0 | n <0 ){
Return 0;
}
If (m <n)
{
Int t = m;
M = n;
N = t;
}
If (m % n)
{
Return getcd (n, (m % n ));
}
Else
{
Return n;
}
}

The main calculation process is divided into three steps:

1. Take the remainder r for the input two natural numbers m> n, so that 0 <= r <n

2. if r is 0 and n is the result, return directly

3. if r is not 0, m = n, n = r is assigned and re-executed from step 1.

The definitions of the public factors of two natural numbers describe the conditions for the calculation results. If the remainder r calculated in step 1 is 0, the smaller number is the public factor. If r! If the value is 0, the relationship between natural numbers m and n can be expressed as: m = kn + r (where k is a natural number ), equations can prove that any number that can divide m must be able to divide n and r. equations can be further deformed into: r = m-kn, it indicates that at the same time, any number of m and n must be able to divide r. That is to say, the set of numbers that can divide m and n is equal to the set of numbers that divide n and r. So the method of separation is established.

Release another version that cyclically implements the Euclidean algorithm.

Copy codeThe Code is as follows: int getcd2 (int m, int n)
{
If (m <0 | n <0 ){
Return 0;
}
If (m <n)
{
Int t = m;
M = n;
N = t;
}
Int cd = 1;
While (1 ){
Int r = m % n;
If (0 = r)
{
Cd = n;
Break;
}
Else {
M = n;
N = r;
}
}
Return cd;
}

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.