- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# C++ Program to Find the GCD and LCM of n Numbers

This is the code to find out the GCD and LCM of n numbers. The GCD or Greatest Common Divisor of two or more integers, which are not all zero, is the largest positive integer that divides each of the integers. GCD is also known as Greatest Common Factor.

The least common multiple (LCM) of two numbers is the smallest number (not zero) that is a multiple of both numbers.

## Algorithm

Begin Take two numbers as input Call the function gcd() two find out gcd of n numbers Call the function lcm() two find out lcm of n numbers gcd(number1, number2) Declare r, a, b Assign r=0 a = (number1 greater than number2)? number1: number2 b = (number1 less than number2)? number1: number2 r = b While (a mod b not equal to 0) Do r = a mod b a=b b=r Return r Done lcm(number1, number2) Declare a a=(number1 greater than number2)?number1:number2 While(true) do If (a mod number1 == 0 and a number2 == 0) Return a Increment a Done End

## Example Code

#include<iostream> using namespace std; int gcd(int m, int n) { int r = 0, a, b; a = (m > n) ? m : n; b = (m < n) ? m : n; r = b; while (a % b != 0) { r = a % b; a = b; b = r; } return r; } int lcm(int m, int n) { int a; a = (m > n) ? m: n; while (true) { if (a % m == 0 && a % n == 0) return a; ++a; } } int main(int argc, char **argv) { cout << "Enter the two numbers: "; int m, n; cin >> m >> n; cout << "The GCD of two numbers is: " << gcd(m, n) << endl; cout << "The LCM of two numbers is: " << lcm(m, n) << endl; return 0; }

## Output

Enter the two numbers: 7 6 The GCD of two numbers is: 1 The LCM of two numbers is: 42

- Related Questions & Answers
- GCD and LCM of two numbers in Java
- Write a C# program to find GCD and LCM?
- Java program to find the LCM of two numbers
- Java Program to Find LCM of two Numbers
- Java Program to Find GCD of two Numbers
- Find LCM of two numbers
- Find any pair with given GCD and LCM in C++
- Find GCD of two numbers
- Program to find LCM of two Fibonnaci Numbers in C++
- Java program to find the GCD or HCF of two numbers
- Find the GCD of N Fibonacci Numbers with given Indices in C++
- Program to find GCD of floating point numbers in C++
- C program to find GCD of numbers using recursive function
- Program to find GCD or HCF of two numbers in C++
- C program to find GCD of numbers using non-recursive function

Advertisements