Greatest common divisor and least common multiple issues
is a small problem, although it is a small problem,
However, it is basic,
Many times,
We are not necessarily able to write it.
First of all, (this paragraph is reproduced from the encyclopedia)
The principle of calculation relies on the following theorem: Theorem: gcd (A, b) = gcd (b,a MoD) (A>b and a mod B is not 0)//That is, the large number of decimal places the decimal, the decimal variable number of the large number. Proof: A can be expressed as A = kb + R, then r = a mod b assumes that D is a number of a, B, a d|a,d|b, and r = a-kb, so D|r D is also (B,a mod b) The number of conventions
Thus (A, b) and (b,a mod b) The number of conventions is the same, and its greatest common divisor is necessarily equal, the certificate or: proof: First step: Make C=GCD (A, b), then set A=MC,B=NC the second step: according to the premise of the R =a-kb=mc-knc= (M-KN) C Step three: According to the second step results that 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, rather than C, and the preceding conclusion contradiction "so that gcd (b,r) =c, then gcd (A, B) =gcd (B,R), the above two methods are the same. The above is proof of this formula for GCD (A, B) =gcd (B,a MoD). Here's the code:
#include <stdio.h>//Recursive ImplementationintgcdintMintN) { if(M <N) {intTMP =m; M=N; N=tmp; } if(n = =0) returnm; Else returnGCD (n,m%n);}}//non-recursive implementationintGCD2 (intMintN) { if(M <N) {intTMP =m; M=N; N=tmp; } if(n = =0) returnm; while(N >0) { intTMP = m%N; M=N; N=tmp; } returnm;}
There are recursive and non-recursive two, for the efficiency of the Code, non-recursive is obviously better!
Then, with the greatest common divisor, we can easily find out least common multiple ~ ~ ~
// Beg least common multiple int GBS (int m,int n) { return m*n/
Of course, although the code is two numbers, but can be pushed to the number of n quickly, as long as one at a time, then the function can be.
Basic algorithm can not forget, refueling.
Euclidean algorithm seeking greatest common divisor