Gcd (greatest common divisor) [calculate the maximum common divisor]

Source: Internet
Author: User
Tags greatest common divisor

The following snippet is copied from the book (structure and interpretation of computer programs 1.2.5)

-----------------------------------------------

The greatest common divisor (GCD) of two integers A and B is defined to be the largest integer that divides both A and B with no remainder.
The idea of the algorithm is based on the observation that, if R is the remainder when a is divided by B, then the common divisors of A and B are precisely the same as the common divisors of B and R. thus, we can use the equation

Gcd (a, B) = gcd (B, R)

To successively reduce the problem of computing a GCD to the problem of computing the GCD of smaller and smaller pairs of integers. For example,

Gcd (246,40) = gcd (40,6)
= Gcd (6, 4)
= Gcd (4, 2)
= Gcd (2, 0)
= 2
Reduces gcd () to gcd (), which is 2. it is possible to show that starting with any two positive integers and specify Ming repeated functions will always eventually produce a pair where the second number is 0. then the GCD is the other number in the pair. this method for computing the GCD is knownEuclid's Algorithm. 42

--------------------------------------------------

The following code works in vc2005

 

# Include "stdafx. H"
# Include <stdio. h>

/*

Function: GCD

Input: a, B

Output: The GCD of integer A and B

*/

Int gcd (int A, int B)
{
If (0 = B)
{
Return;
}
Else
{
Return gcd (B, A % B );
}
}

 

Int _ tmain (INT argc, _ tchar * argv [])
{
Int r = gcd (206, 40 );
Printf ("r = % d", R );

R = gcd (40,206 );
Printf ("r = % d", R );
Return 0;
}

 

Remark:Euclid's algorithm: Euclidean Algorithm

 

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.