LCM program in C++

LCM program in C++

本文关键字:C++ in program LCM      更新时间:2023-10-16
#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 语句没有执行我想要它要执行的操作,因为当产品和 product2 相等时,不会打印任何内容。这个小问题的解决方案是什么?

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

试试这个

//#include "stdafx.h"
#include <iostream>
#include <conio.h>
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;
int num_limit = num1 * num2,LCM;
for (int i = 1; i <= num_limit; i++)
{
LCM = num1 * i;
// test for when multiples are equal
if (LCM%num2==0) break;
}
cout << "The LCM of " << num1 << " and " << num2 << " is: " << LCM;
_getch();// replace with getch(); if didn't work
}