Find LCM and HCF of 3 numbers in C++

In this post we will understand how to find the LCM and the HCF of 3 numbers, then we will implement the approach in C++, lets start with the definition:

HCF ( Highest Common Factor): The HCM of 3 numbers is Highest common factor of those three numbers. For e.g. let’s say we have 20, 30 and 40. So the HCF will be 10 as 10 is the highest common factor of 20, 30 as well as 40. You must know how to calculate HCF of numbers.

LCM ( Lowest Common Multiple): LCM is the lowest common Multiple of those numbers. For e.g. LCM of 5, 7 and 9 is 45, as 45 is the least number which is divisible by all the three numbers.

Now let’s discuss how can we write a code to implement above examples:

How Code Works:

  • Given 3 numbers a, b and c, let’s write two separate functions to find the LCM & HCF respectively.
  • Let’s calculate the LCM by first finding the maximum of the 3 numbers and then check for the LCM using the for loop.
  • similarly using for loop start checking the HCF by using condition of finding HCF.
  • Both functions will return LCM and HCF respectively.

Now let’s write the code for the same.

We can also find the HCF and LCM of Two numbers

Program to find LCM and HCF of 3 numbers in C++:

You can also execute this code on our online compiler.

#include<iostream>
using namespace std;

int lcm(int, int, int);
int hcf(int, int, int);
int main()
{
        int a,b,c;
        int LCM, HCF;
        cout<<"Enter 1st number: ";
        cin>>a;
        cout<<"Enter 2nd number: ";
        cin>>b;
        cout<<"Enter 3rd number: ";
        cin>>c;

        LCM = lcm(a,b,c);
        HCF = hcf(a,b,c);
        cout<<"LCM of "<<a<<","<<b<<","<<c<<" is = "<<LCM<<endl;
        cout<<"HCF of "<<a<<","<<b<<","<<c<<" is = "<<HCF<<endl;
        return 0;
}

int lcm(int x,int y, int z)
{
        long max,lcom, count, flag=0;
        if(x>=y&&x>=z)
                max=x;
        else if(y>=x&&y>=z)
                max=y;
        else if(z>=x&&z>=y)
                max=z;
        for(count=1;flag==0;count++)
        {
                lcom=max*count;
                if(lcom%x==0 && lcom%y==0 && lcom%z==0)
                {
                        flag=1;
                }
        }
        return lcom;
}

int hcf(int p, int q, int r)
{
        int gcf=1,flag=0, count;
        for(count=1; flag==0;count++)
        {
                if(p%count==0&&q%count==0&&r%count==0)
                        gcf=count;
                if(count>p&&count>q&&count>r)
                {
                        flag=1;
                }
        }
        return gcf;
}

OUTPUT:

Enter 1st number: 11
Enter 2nd number: 22
Enter 3rd number: 33
LCM of 11,22,33 is = 66
HCF of 11,22,33 is = 11

Comment below in case you have more efficient code or want to discuss about the above program.

1 thought on “Find LCM and HCF of 3 numbers in C++”

Leave a Comment