要求最小公倍数,需要求最大公约数,由于:最小公倍数 = 两数相乘/最大公约数
求最大公约数,可以利用辗转相除法,详细可参考:https://blog.csdn.net/huyr_123/article/details/81670972
利用辗转相除法求取最大公约数函数如下:
int gcd(int a,int b)
{
if(a<b)
{
int temp = a;
a = b;
b = temp;
}
if(a%b==0) return b;
else return gcd(b,a%b);
}求得最大公约数问题迎刃而解,完整代码如下:
#include<iostream>
using namespace std;
int gcd(int a,int b)
{
if(a<b)
{
int temp = a;
a = b;
b = temp;
}
if(a%b==0) return b;
else return gcd(b,a%b);
}
int main()
{
int ans;
int a,b;
cin>>a>>b;
int tmp = gcd(a,b);
ans = a*b/tmp;
cout<<ans;
return 0;
}
京公网安备 11010502036488号