C++ : Find HCD and LCM in one line code














































C++ : Find HCD and LCM in one line code



HCF and LCM using STL(Standard Template Library)

There is an easy way to find HCF(Highest Common Factor) using STL library <algorithm>.
To find HCF, we use :-

 __gcd(int a, int b) 
The only thing to watch is that the numbers that we give as inputs must be integers.

EXAMPLE

Input:

#include <iostream> 
#include <algorithm>  
  
using namespace std; 
  
int main() 
{
int a = 18;
int b = 21;

      cout << "HCF = " << __gcd(a, b) << "\n"; 
// cout << __gcd(18.0, 21) .................This causes error because no typecasting occurs
cout << "LCM = " << (a*b)/__gcd(a, b);

Output:

HCF = 3
LCM = 126

Comments