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