Euclidean algorithm
Euclidean algorithm is also called the greatest common divisor method, is the algorithm to find two integers.
Of course, can also seek least common multiple.
Algorithm implementation
In fact, the implementation principle of the algorithm is that there is a b an integer two, each time a number r = a % b , and then put b into a the position, put r to b the position, recursive call.
That's the gcd(a, b) { return gcd(b, a%b); } way it is.
The end condition is when a%b == 0 the time is stopped.
Greatest common divisor
////Main.cpp//Euclidean////Created by Alps on 15/3/28.//Copyright (c) 2015 Chen. All rights reserved.//#include <iostream>using namespace STD;intgcdintAintb) {if(A%b = =0) {returnb }returnGCD (b, a%b);}intMainintargcConst Char* argv[]) {intA = -, B = -;printf("%d\n", GCD (A, b));return 0;}
The above is the greatest common divisor of the request. In fact, through this also can seek least common multiple.
Least common multiple
Least common multiple, the product of which is a b divided by their two greatest common divisor, is their least common multiple. The code is as follows:
intintint b){ return (a * b)/gcd(a, b);}
That would be all right.
Algorithm Learning-Euclidean algorithm (c + + implementation)