on Leave a Comment

C++ Program to Find LCM of Two Numbers

LCM of two numbers is least common multiple of both number.

C++ Program to Find LCM of Two Numbers

#include <iostream>
using namespace std;
int main()
{
    int a,b,x;
    cout<<"Enter two numbers ";
    cin>>a>>b;
    for(x=1;x<=a*b;x++)
        if(x%a==0 && x%b==0)
            break;
    cout<<"\nLeast Common Multiple(LCM) of "<<a<<" and "<<b<<" is "<<x;
    return 0;
}

OUTPUT:

Enter two numbers 3
9

Least Common Multiple(LCM) of 3 and 9 is 9

Example 2: C++ Program to Find LCM of Two Numbers

#include <iostream>
using namespace std;
int main()
{
    int a,b,x;
    cout<<"Enter two numbers ";
    cin>>a>>b;
    for(x=a>b?a:b;x<=a*b;x++)
        if(x%a==0 && x%b==0)
            break;
    cout<<"\nLeast Common Multiple(LCM) of "<<a<<" and "<<b<<" is "<<x;
    return 0;
}

OUTPUT:

Enter two numbers 4
6

Least Common Multiple(LCM) of 4 and 6 is 12

Example 3: C++ Program to Find LCM of Two Numbers

#include <iostream>
using namespace std;
int main()
{
    int a,b,x;
    cout<<"Enter two numbers ";
    cin>>a>>b;
    for(x=a>b?a:b;x<=a*b;x=x+(a>b?a:b))
        if(x%a==0 && x%b==0)
            break;
    cout<<"\nLeast Common Multiple(LCM) of "<<a<<" and "<<b<<" is "<<x;
    return 0;
}

OUTPUT:

Enter two numbers 12
18

Least Common Multiple(LCM) of 12 and 18 is 36

See also:




0 comments:

Post a Comment