Problem: Fast greatest common divisor of positive integers a, b?
Euclidean algorithm (also known as the Euclidean method)
Theorem: gcd (b) = gcd (a,a mod b)
Proof: For any positive integer, a, B. If a>b, there are a=k*b+r namely r=a-k*b = r=a MoD B.
Assuming D is the number of conventions for a, B, then a=a1*d,b=b1*d.
and r=a1*d-k*b1*d= (A1-K*B1) *d and D is also the approximate number of R and the (A,R) Convention
The number of conventions (a, B) is the number of conventions (A,R). So gcd (b) =gcd (a,a mod b).
/** * for greatest common divisor * Euclidean algorithm, also known as the Euclidean method, is used to calculate the number of two integers a, B, greatest common divisor. * Its calculation principle relies on the following theorem: Gcd (A, b) = gcd (b,a MoD) * * @author heartraid*/ Public classEucliddivisor { Public Static intGetdivisor (intAintb) { if(a%b==0)returnb; if(b%a==0)returnA; returnA>=b?getdivisor (a,a%b): Getdivisor (a,b%a); } Public Static voidMain (string[] args) {System. out. println (Eucliddivisor.getdivisor ( A,8)); }}
Extension: quick to find positive integers, a, B, least common multiple? first, the greatest common divisor c= (A, A, a, b) is obtained, and then a*b/c can be used.
Euclid has to beg for greatest common divisor.