#include <iostream>
using std::cout;
using std::cin;
int main()
{
int num1 = 0;
int num2 = 0;
cout << "Please enter two numbers (remember to put
a space between them):\n";
cin >> num1 >> num2;
const int num_limit = num1 * num2;
for (int i = 1; i <= num_limit; i++)
{
int product = num1 * i;
int product2 = num2 * i;
// test for when multiples are equal
if (product == product2)
{
cout << "The LCM of " << num1 << " and " <<
num2 << " is: ";
}
}
}
我正在尝试从用户输入的两个整数中获取LCM。 for循环中的if语句没有按照我的预期去做,因为product和product2相等时不会显示任何内容。这个小问题的解决方案是什么?
答案 0 :(得分:1)
int gcd(int a,int b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
int lcm(int a,int b)
{
//Efficient Solution
// a*b=gcd(a,b)*lcm(a,b)
return (a*b)/gcd(a,b);
}
int main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int a,b;
cin>>a>>b;
cout<<lcm(a,b);
return 0;
}
输出
15 12
60
答案 1 :(得分:0)
尝试一下
Foo