Euclidean subtraction greatest common divisor

What is the Euclidean subtraction

Our primary method (should be the primary right) learned greatest common divisor is Euclidean, in fact, there is another way, just 12 years of compulsory education were not mentioned, and that is removed subtraction. Its basic principle is: the number of large numbers is reduced, until the two numbers are equal, that is the common denominator.

For chestnuts

a        b       |a - b|

88    156

88    68     156 - 88

20    68      88 - 68

20    48      68 - 20

20    28      48 - 20

20    8        28 - 20

12    8        20 - 8

4      8        12 - 8

4      4         8 - 4

a == b => 4 greatest common divisor

Recursive

int GCD(int a, int b)
{
    if (a == b)
        return a;
    else if (a > b)
        return GCD (a, b);
    else
        return GCD(b, a);
}

 Iterative implementation

int GCD(int a, int b)
{
    while(a == b)
    {
        if (a > b) a -= b;
        else b -= a;
    }
    return a;
}

 A subtraction removed to better understand, and secondly to write better programs, home travel Required method!

Guess you like

Origin www.cnblogs.com/HuangWj/p/11261870.html