C++ program to find LCM and HCF of two numbers and show their factors (logic explained step by step)

C++ program to find LCM and HCF of two numbers and show their factors

Here is the proper c++ code to find LCM and HCF of two numbers and show their factors. This program is developed by using for loop and control structures means if() statements.

 Steps
User side
1: User asked to enter first number
2: Screen shows its factors.
3: User asked to enter second number
4: Screen shows its factors.
5: Screen shows the highest common factor and least common factor of two numbers .
Developer side
1: Declare variables that are going to be used in program .
2: Input first number from user
3: Start a for loop from one to the number recently entered by user and check if the modulus of that number and counter is equal to zero, show the counter. (these are the factors of that number).
4: Input second number from user
5: Repeat step number 3 to calculate and show the factors for second number.
6: To calculate highest common factor start a for loop from one to less than the biggest number entered by the user.
7: In the loop check if the modulus of both the numbers with counter is equal to zero then show it, it is the highest common factor of both numbers .
8: To find the least common factor of both the numbers do the following 
LCM=(a*b)/HCF;
9: Show the value of 'LCM' because it contains the least common factor of both the numbers.
10: Program ends here.

Code:
#include<iostream>
using namespace std;

int main()
{      //Variable declaration
       int a,b;
       int i;
       float LCM,HCF;
       //heading
       cout<<"\t\"LCM of two numbers\""<<endl;
       cout<<"Enter first number";
       cin>>a;
       cout<<"Its Factors are "<<endl;
       for(i=1;i<=a;++i)
  {
      if(a%i==0)
         cout<<i<<endl;
  }

       cout<<"Enter first number";
       cin>>b;
       cout<<"Its Factors are "<<endl;
       for(i=1;i<=b;++i)
  {
      if(b%i==0)
         cout<<i<<endl;
  }

      
       //heading
       cout<<"\t\"HCF of two numbers\""<<endl;
       for(i=1; i<=a || i<=b; ++i)
    {
        if(a%i==0 && b%i==0)  
            HCF=i;
    }
       cout<<"HCF = "<<HCF<<endl;
       LCM=(a*b)/HCF;
       cout<<"LCM of the numbers is equal to ="<<LCM<<endl;
       system("pause");
       return 0;
}
Output:

Comments