
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ Program for Common Divisors of Two Numbers?
Here we will see how we can get the number of common divisors of two numbers. We are not going to find all common divisors, but we will count how many common divisors are there. If two numbers are like 12 and 24, then common divisors are 1, 2, 3, 4, 6, 12. So there are 6 common divisors, so the answer will be 6.
Algorithm
countCommonDivisor(a, b)
begin count := 0 gcd := gcd of a and b for i := 1 to square root of gcd, do if gcd is divisible by 0, then if gcd / i = i, then count := count + 1 else count := count + 2 enf if end if done return count end
Example
#include<iostream> #include<cmath> using namespace std; int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } int countCommonDivisors(int a,int b) { int gcd_val = gcd(a, b); //get gcd of a and b int count = 0; for (int i=1; i<=sqrt(gcd_val); i++) { if (gcd_val%i==0) { // when'i' is factor of n if (gcd_val/i == i) //if two numbers are same count += 1; else count += 2; } } return count; } main() { int a = 12, b = 24; cout << "Total common divisors: " << countCommonDivisors(a, b); }
Output
The differences array: 6 5 10 1
- Related Articles
- Python Program for Common Divisors of Two Numbers
- Java Program for Common Divisors of Two Numbers
- C++ Program for the Common Divisors of Two Numbers?
- Program to count number of common divisors of two numbers in Python
- Greatest common divisors in Python
- Check if sum of divisors of two numbers are same in Python
- Write a program to calculate the least common multiple of two numbers JavaScript
- Print the kth common factor of two numbers
- JavaScript Program for find common elements in two sorted arrays
- Count common prime factors of two numbers in C++
- Divisors of n-square that are not divisors of n in C++ Program
- Count the number of common divisors of the given strings in C++
- Position of rightmost common bit in two numbers in C++
- Python Program for GCD of more than two (or array) numbers
- C++ Program for GCD of more than two (or array) numbers?

Advertisements