-2
#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: "; 
        }

     }
}

I'm trying to get the LCM from two integers which the user enters. The if statement within the for loop isn't doing what I intended it to do, as nothing prints when product and product2 are equal. What is the solution to this little problem?

Njgardner90
  • 61
  • 1
  • 7

2 Answers2

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;
}

Output

15 12
60
Michael Kotzjan
  • 2,093
  • 2
  • 14
  • 23
  • This is the correct solution based on the Euclidean algorithm. If anyone is in doubt, try running this and the accepted answer on a couple of 6-digit numbers. – nielsen Mar 23 '21 at 11:42
0

Try this out

//#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
}
Michael Kotzjan
  • 2,093
  • 2
  • 14
  • 23
Mostafa Ayaz
  • 480
  • 1
  • 7
  • 16