Code:
//Greatest Common Divisor Public intgcdintPintq) { if(q = 0)returnp; returnGCD (q, p%q); }//least common multiple Public intLcmintPintq) { intPQ = p *Q; returnPQ/gcd (P,Q); }
Test:
@Test publicvoid Go () { int p = 5,q =17; SYSTEM.OUT.PRINTLN (P+ "and" +q+ "greatest common divisor:" +gcd (p,q) "); SYSTEM.OUT.PRINTLN (P+ "and" +q+ "of least common multiple:" +LCM (p,q)); } Operating results: 5 and 17 of greatest common divisor:1 5 and 17 of least common multiple:85
Principle:
The first greatest common divisor used the Euclidean algorithm, which was invented 2,300 years ago, and the approximate principle is:
If there are two nonnegative integers p, q, if q==0, then greatest common divisor is p; otherwise, the greatest common divisor of P and Q is the remainder of p divided by Q and the greatest common divisor of Q.
The second least common multiple is much simpler.
Formula: least common multiple = Two integer of the Product ÷ greatest common divisor
is not so easy!
Greatest common divisor and least common multiple--java implementations