Greatest common divisor
1. Using the most basic method of loop traversal
2. Using the divide-and-toss method
3. Subtraction with the use of the tossing phase
See also:http://baike.baidu.com/view/47637.htm
1#include <iostream>2 using namespacestd;3 4 intCommondivisor (intXinty);5 intCommonmultiple (intXinty);6 intCommonDivisor1 (intXinty);7 intCommonMultiple2 (intXinty);8 intCommonDivisor2 (intXinty);9 intGetdif (intXinty);Ten intMain () One { A intA, B; -cout <<"Please input the integer:"; -Cin>>a >>b; the -Cout<<commondivisor (b) <<Endl; -Cout<<commonmultiple (b) <<Endl; -cout<<"-----------------------------------"<<Endl; +Cout<<commondivisor1 (b) <<Endl; -Cout<<commonmultiple2 (b) <<Endl; + Acout<<"-----------------------------------"<<Endl; atCout<<commondivisor2 (b) <<Endl; - -cout<<Endl; - - } - in intCommonDivisor1 (intXinty) - { to //greatest common divisor must be between 1 and x and y smaller values, so a smaller value between x and Y starts looping through, finding the largest number of conventions + intStart =x; - if(X >y) theStart =y; * for(inti = start; I >=1; i--) $ {Panax Notoginseng if(x% i = =0&& y% i = =0) - returni; the } + return 1; A } the + intCommonDivisor2 (intXinty) - { $ //tossing and subtracting $ if(x%2==0&& y%2==0) - return 2* COMMONDIVISOR2 (X/2, Y/2); - Else the { - returngetdif (x, y);Wuyi } the } - Wu intGetdif (intXinty) - { About intlarger =x; $ intsmaller =y; - if(X <y) - { -larger =y; Asmaller =x; + } the intdif = larger-smaller; - if(DIF = =smaller) $ returndif; the Else the returngetdif (smaller, dif); the } the - intCommondivisor (intXinty) in { the //Euclidean Method the if(x==0) About returny; the returnCommondivisor (y%x, x); the } the intCommonmultiple (intXinty) + { - //least common multiple is the value of x and Y multiplied by the greatest common divisor of x and y . the intcd =commondivisor (x, y);Bayi return((x * y)/CD); the } the intCommonMultiple2 (intXinty) - { - //least common multiple is a value that must be between the greater of X and Y and the XY product, so a small-to-large traversal finds this number the intStart =x; the intend = x *y; the if(X <y) theStart =y; - for(inti = y; Y <= end; i++) the { the if(i% x = =0&& I% y = =0) the returni;94 } the returnend; the}
Greatest common divisor and least common multiple algorithm implementation