Finding LCM

Normal iterative way:

#include <iostream>

using namespace std;

int main()
{
    int a,b,x,i,lcm;
    cout<<"Enter one value: "<<endl;
    cin>>a;
    cout<<"Enter another value: ";
    cin>>b;
    x=max(a,b);
    for(i=x;;i++)
    {
        if(i%a==0 && i%b==0)
        {
            lcm=i;
            break;
        }
    }
    cout<<"LCM is "<<lcm<<endl;

    return 0;
}

Using GCD:
This way has a chance of overflow.

#include <iostream>

using namespace std;

int gcd(int a,int b)
{
    return b==0 ? a : gcd(b,a%b);
}

int main()
{
    int c,d,lcm;
     for(;;)
    {
        cout<<"Enter any number:"<<endl;
        cin>>c;
        cout<<"Enter another number:"<<endl;
        cin>>d;

        lcm=(c*d)/gcd(c,d);

        cout<<"LCM is "<<gcd(c,d)<<endl<<endl;
    }
    return 0;
}

Using GCD:
This way hasn’t a chance of overflow. It’s the best way.

#include <iostream>

using namespace std;

int gcd(int a,int b)
{
    return b==0 ? a : gcd(b,a%b);
}

int main()
{
    int c,d,lcm;
     for(;;)
    {
        cout<<"Enter any number:"<<endl;
        cin>>c;
        cout<<"Enter another number:"<<endl;
        cin>>d;

        lcm=(c*d)/gcd(c,d);

        cout<<"LCM is "<<gcd(c,d)<<endl<<endl;
    }
    return 0;
}

Leave a comment