# Using _c language based on Euclidean algorithm

Source: Internet
Author: User

Euclid's algorithm is called the Euclidean method, which is used to find the common factor of the known m and n two natural numbers. Combine the procedure to explain the specific situation of the division.

First look at recursive implementations:

Copy Code code 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, the input of two natural number M > n to take the remainder R, so that 0<= R < n

2, if R for 0,n is the result of the request, direct return

3, R is not 0, the assignment m=n,n=r starts at step 1 and then executes again

The definition of the common factor of two natural numbers shows the condition of the result of the calculation. If the remainder r = 0 is calculated in step 1, the smaller number is the common factor. If r!=0, the relationship between the natural number m and n can be expressed as: M = kn + R (where k is a natural number), the equation can prove that any number that can divide m must be divisible by N and R; the equation is further deformed to: R = m-kn, which means that any number that divides m and N at the same time is bound to be divisible by R. In other words, the set of numbers that divide m and n is equal to the set of numbers that divide N and R. So the method of dividing the divide is established.

Then publish a loop to implement the Euclidean algorithm version.

Copy Code code 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;
}

Related Keywords:

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.