Euclidean algorithm

Euclidean Algorithm, also called division by turn, or gcd for short, is used to calculate the greatest common divisor of two integers

Define gcd(a,b) as the greatest common divisor of integers a and b

The proof process is transferred from the blog of a big guy

Lemma: gcd(a,b)=gcd(b,a%b)

  Prove:

    设 r=a%b , c=gcd(a,b)

    Then a=xc , b=yc , where x , y are relatively prime

    r=a%b=a-pb=xc-pyc=(x-py)c

    while b=yc

    It can be seen that y and x-py are relatively prime

    Prove:

                Suppose y is not coprime to x-py

                Let y=nk , x-py=mk , and k>1 (because of coprime)

                Bring y to get

                x-pnk=mk

                x=(pn+m)k

                则 a = xc = (pn + m) kc, b = yc = nkc

                Then the greatest common divisor of a and b at this time is kc not k

                Contradicting with the original proposition, then y and x-py are relatively prime

    Since y and x-py are relatively prime, the greatest common divisor of r and b is c

    即 gcd(b,r)=c=gcd(a,b)

    certified

  When a%b=0, gcd(a,b)=b

 


Let's simulate the process of tossing and dividing:

Find the greatest common factor of two positive numbers 8251 and 6105.
(Analysis: Divide by twist and turn → the remainder is zero → get the result)
Solution: 8251=6105×1+2146
Obviously, the greatest common factor of 8251 and 6105 must also be the factor of 2146. Similarly, the common factor of 6105 and 2146 must also be the factor of 8251. So the greatest common factor of 8251 and 6105 is also the greatest common factor of 6105 and 2146.
6105=2146×2+1813
2146=1813×1+333
1813=333×5+148
333=148×2+37
148=37×4+0
Then 37 is the greatest common factor of 8251 and 6105.

 

The whole process is: there are two numbers ab, where a>b

a = b*(a/b) + a%b

Then, b becomes the a of the next formula, and a%b, that is, the remainder of the previous formula becomes the b of the next formula

b = (a%b)*(b/(a%b)) + (b%(a%b))

In this way, when the remainder is 0, the greatest common divisor is obtained, which is the value of a

 


Algorithm template:

inline int gcd(int a,int b)
{
	if(!b)
		return a;
	else
		return gcd(b,a%b);	
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326390191&siteId=291194637