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.
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int gcd(int x, int y)
{
int r = 0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while (a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
int lcm(int x, int y)
{
int a;
a = (x > y) ? x : y; // a is greater number
while (true)
{
if (a % x == 0 && a % y == 0)
return a;
++a;
}
}
int main(int argc, char **argv)
{
cout << "Enter the two numbers: ";
int x, y;
cin >> x >> y;
cout << "The GCD of two numbers is: " << gcd(x, y) << endl;
;
cout << "The LCM of two numbers is: " << lcm(x, y) << endl;
;
return 0;
}
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]Related Posts:
- Practice Computer Science MCQs
- Apply for C++ Internship
- Check Programming Books
- Check Computer Science Books
- Apply for Computer Science Internship