To Find HCF LCM in C++


Q.Write a C++ program to find HCF(GCD) and LCM ?

#include <iostream>      
using namespace std;
  
int main()
{ 
    int a, b, i, j, t, gcd, lcm;
    cout <<"Enter two integers: ";
    cin >> a >> b;
    i = a;
    j = b;
    while (j > 0) 
    {
        t = j;
        j = i % j;
        i = t;
    }
    gcd = i;
    lcm = (a*b)/gcd;
    cout << "Greatest common divisor(GCD or HCF) of "<< a <<
    " and "<< b <<" is " << gcd << endl;
    cout << "Least common multiple of "<< a <<" and "<< b <<" is " << lcm ;
	return 0;    
} 

Q. Write an algorithm to find HCF(GCD) and LCM ?

1. Start
2. Input two integers `a` and `b`.
3. Initialize two temporary integer variables:
    - `i` = `a`
    - `j` = `b`
4. Compute GCD using Euclidean Algorithm:
    - While `j` is greater than 0:
    - Assign `t` = `j`
    - Assign `j` = `i % j` (remainder of `i` divided by `j`)
    - Assign `i` = `t`
    - After the loop ends, `i` holds the GCD of `a` and `b`.
5. Assign `gcd` = `i`.
6. Compute LCM using the formula:
    - `lcm` = (`a` * `b`) / `gcd`.
7. Output the values of `gcd` and `lcm`.
8. End 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.