 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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 for the Common Divisors of Two Numbers?
What are Common Divisors?
The common divisors of two numbers are the numbers that are divisors of both. A number is said to divide another number if it leaves no remainder when divided.
- For example, 3 divides 12 since 12 / 3 = 4 (no remainder).
- But 5 does not divide 12 because 12 / 5 = 2 with a remainder of 2.
Understanding with an Example
Let's take two numbers, 12 and 18. We list all the divisors of both numbers and identify the common ones.
Divisors of 12: 1, 2, 3, 4, 6, 12 Divisors of 18: 1, 2, 3, 6, 9, 18 Common Divisors: 1, 2, 3, 6
Greatest Common Divisor (GCD)
The greatest among the common divisors is called the Greatest Common Divisor (GCD). It is usually denoted by GCD(a, b) or (a, b). For the above example:
GCD(12, 18) = 6
Least Common Multiple (LCM)
The GCD helps in calculating the Least Common Multiple (LCM), which is the smallest positive number that is a multiple of both. The formula is:
LCM(a, b) = (a x b) / GCD(a, b)
For example,
LCM(12, 18) = (12 x 18) / 6 = 216 / 6 = 36
Example 1: Common Divisors Using a Loop
This program uses a loop to check numbers from 1 up to the smaller of the two values and prints those that divide both without a remainder.
#include<iostream> using namespace std; int main() { int n1, n2, i; n1 = 10; n2 = 20; cout << "Common divisors of " << n1 << " and " << n2 << " are: "; for(i = 1; i <= n1 && i <= n2; ++i) { if(n1 % i == 0 && n2 % i == 0) { cout << i << " "; } } cout << endl; return 0; }  When you run the above code, the output will be:
Common divisors of 10 and 20 are: 1 2 5 10
Example 2: Common Divisors Using a Function
This program uses a function to print all common divisors. It takes two numbers as parameters and prints all numbers that divide both without a remainder.
#include<iostream> using namespace std; // Function to print common divisors void printCommonDivisors(int a, int b) { int minVal = (a < b) ? a : b; cout << "Common divisors of " << a << " and " << b << " are: "; for (int i = 1; i <= minVal; i++) { if (a % i == 0 && b % i == 0) { cout << i << " "; } } cout << endl; } int main() { int a = 10, b = 20; printCommonDivisors(a, b); return 0; }  When you run the above code, the output will be:
Common divisors of 10 and 20 are: 1 2 5 10
