#include <iostream>using namespace std;//Example://2 | 8 6//----------//4 3//so: gcd=2,lcm=2*4*3=24//for Greatest common divisor: the Division method//1. A÷b, the R is the resulting remainder (0≤R<B)//If R = 0, the algorithm ends; b is the answer. 2. Swap: Place A←b,b←r and return the first step int gcd1 (int m, int n) {int r;while (n) {r = m% N;m = N;n = r;}; return m;} int gcd2 (int m, int n) {if (n) return GCD1 (n, m%n); Elsereturn m;} Least common multiple: Formula method//Because the product of two numbers equals the product of greatest common divisor and least common multiple of these two numbers. That is (A, b) x[a,b]=axb. Therefore, to find the least common multiple of two numbers, we can first find out their greatest common divisor, and then use the above formula to find their least common multiple. int LCM (int m, int n) {return (m*n)/GCD1 (m, n);} int main () {int m, n;cout<< "input numbers:" <<endl;while (cin>>m) {cin>>n;if (m<=0 | | n<=0) {cerr<< "Error input!!!" <<endl;cout<< "Input numbers:" <<endl;continue;} cout<< "gcd (" <<m<< "," <<n<< ") =" <<GCD1 (m, N) <<endl;cout<< "LCM (" <<m<< "," <<n<< ") =" <<LCM (m, n) <<endl;cout<< "input-numbers:" << Endl;} return 0;}
Greatest common divisor, least common multiple algorithm