New Tutorials:

# C++ Program to find GCD and LCM

Hello Everyone!

In this tutorial, we will learn how to find the GCD and LCM of the given two numbers, in the C++ programming language.

So let's first understand the terminologies involved here.

### What is a GCD?

Greatest Common Divisor or GCD of two numbers is the maximum possible number that perfectly divides (remainder 0) both the numbers togother.

Example:

Consider two numbers to be 2 and 3. Now 12 has both 2 and 3 as its factors but 6 is the least possible number that has both 2 and 3 as its factors or 6 is the least number that is a multiple of both 2 and 3. Hence 6 is the LCM of 2 and 3.

### What is a LCM?

Least Common Multiple or LCM of two numbers is the least possible number that is a multiple of both the numbers or that has both the numbers as its factors.

Example:

Consider two numbers to be 20 and 30. Now 1 perfectly divides both 20 and 30. Even 2 and 5 perfectly divides both 20 and 30. But 10 is the largest number that divides both 20 and 30 together and hence is considered to be the GCD of 20 and 30.

Code:

``````#include <iostream>
using namespace std;

int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " =====  Program to find the GCD and LCM of two numbers ===== \n\n";

//variable declaration
int n1, n2, i;

//variable declaration and initialization
int gcd = 1, lcm = 1;

//taking input from the command line (user)
cout << " Enter the two numbers you want to find the GCD and LCM of : \n\n";
cin >> n1 >> n2;

//logic to calculate the GCD and LCM of the two numbers
for ( i = 1; i < 1000; i++)
{
//i is the least value that perfectly divides both the numbers and hence the GCD
if ((n1 % i == 0) && (n2 % i == 0))
{
gcd = i;
}
}

lcm = (n1 * n2) / gcd;

cout << " \n\nThe GCD of the two numbers : " << n1 << " and " << n2 << " is : " << gcd;
cout << " \n\nThe LCM of the two numbers : " << n1 << " and " << n2 << " is : " << lcm << "\n\n";
cout << "\n\n\n";

return 0;
}``````

Output:

Keep Learning : )