有关数学原理可以自行百度
简单陈述如下:A和B的乘积除以A和B的最大公约数即为答案。
然后递归实现最大公约数的程序 在不极端要求性能的情况下可以通过加一个func(b, a)
来确保a
大b
小,从而简化递归程序的判断逻辑。(注:这个简化方法我是从别人的代码里学习来的,由于不能确认最开始这样写的作者,此处不注明借鉴来源)
#include <iostream> using namespace std; int func(int a, int b){ if(a < b) func(b, a); //确保 a>=b //辗转相除求解问题 if(b==0) return a; else return func(b, a%b); } void testFunc(){ //测试上面的辗转相除法的正确性 cout << func(2, 10) << endl; cout << func(10, 2) << endl; cout << func(5, 7) << endl; } int main(){ //求A和B的最大公约数,然后将A*B除以最大公约数即得最小公倍数 //testFunc(); int a, b; while(cin >> a >> b){ cout << a*b/func(a, b) << endl; } return 0; }