C++ Program to Find the GCD and LCM of N Numbers

This is a C++ Program to find GCD and LCM of given two numbers.

Here is source code of the C++ Program to Find the GCD and LCM of n Numbers. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include<iostream>
  2. #include<conio.h>
  3. #include<stdlib.h>
  4.  
  5. using namespace std;
  6.  
  7. int gcd(int x, int y)
  8. {
  9.     int r = 0, a, b;
  10.     a = (x > y) ? x : y; // a is greater number
  11.     b = (x < y) ? x : y; // b is smaller number
  12.  
  13.     r = b;
  14.     while (a % b != 0)
  15.     {
  16.         r = a % b;
  17.         a = b;
  18.         b = r;
  19.     }
  20.     return r;
  21. }
  22.  
  23. int lcm(int x, int y)
  24. {
  25.     int a;
  26.     a = (x > y) ? x : y; // a is greater number
  27.     while (true)
  28.     {
  29.         if (a % x == 0 && a % y == 0)
  30.             return a;
  31.         ++a;
  32.     }
  33. }
  34.  
  35. int main(int argc, char **argv)
  36. {
  37.     cout << "Enter the two numbers: ";
  38.     int x, y;
  39.     cin >> x >> y;
  40.     cout << "The GCD of two numbers is: " << gcd(x, y) << endl;
  41.     ;
  42.     cout << "The LCM of two numbers is: " << lcm(x, y) << endl;
  43.     ;
  44.     return 0;
  45. }

Output:

$ g++ GCDLCM.cpp
$ a.out
 
Enter the two numbers: 
5
8
The GCD of two numbers is: 1
The LCM of two numbers is: 40
 
Enter the two numbers: 
100
50
The GCD of two numbers is: 50
The LCM of two numbers is: 100

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement

Here’s the list of Best Books in C++ Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.