1 ImportJava.util.Scanner;2 3 Public classZuidagongyueshuclass {4 5 Public Static voidMain (string[] args) {6Scanner in =NewScanner (system.in);7 intA =in.nextint ();8 intb =in.nextint ();9 while(b! = 0) {Ten intr = a%b; OneA =b; Ab =R; - } - System.out.println (a); the in.close (); - } -}
Code from MOOC China Onge 0 Basic Learning Java
The core algorithm here is:
1 while (b! = 0) {2 int r = a% b; 3 A = b; 4 b = R; 5 }
In this example, the original A, b in the user input of the two integers, after the calculation of this cycle, a will store the final result is greatest common divisor.
The proof method is as follows: (from Baidu Encyclopedia)
Certificate Law One
A can be expressed as A = kb + R (A,b,k,r are positive integers, and r<b), then r = a mod b
Suppose D is a number of the conventions of A, B, which are recorded as d|a,d|b, that is, A and B can be divisible by D.
While r = a-kb, dividing both sides by d,r/d=a/d-kb/d=m, the right side of the equation shows that M is an integer, so d|r
So d is also the number of B,a mod B conventions
Assuming D is the number of B,a mod b conventions, then d|b,d| (A-k*b), K is an integer,
And then D|a. So d is also the number of conventions for a, b
therefore (b) and (b,a mod b) The number of conventions is the same, and its greatest common divisor is necessarily equal, to be proven.
Certificate Law II
First step: Make C=GCD (A, b), then set A=MC,B=NC
Step two: Know R =a-kb=mc-knc= (M-KN) c
Step three: According to the second step, C is the factor of R.
Fourth step: can determine m-kn and n reciprocity "otherwise, can be set M-kn=xd,n=yd, (d>1), then m=kn+xd=kyd+xd= (ky+x) d, then a=mc= (ky+x) DC,B=NC=YCD, so A and B greatest common divisor ≥cd, not C, Contradiction with the previous conclusion "
So that gcd (B,r) =c, and then gcd (A, B) =gcd (B,R), the proof
"170723" a concise algorithm for seeking greatest common divisor