Common Divisors of Two Numbers
Last Updated :
13 Apr, 2023
Given two integer numbers, the task is to find count of all common divisors of given numbers?
Examples :
Input : a = 12, b = 24
Output: 6
// all common divisors are 1, 2, 3,
// 4, 6 and 12
Input : a = 3, b = 17
Output: 1
// all common divisors are 1
Input : a = 20, b = 36
Output: 3
// all common divisors are 1, 2, 4
It is recommended to refer all divisors of a given number as a prerequisite of this article.
Naive Solution
A simple solution is to first find all divisors of first number and store them in an array or hash. Then find common divisors of second number and store them. Finally print common elements of two stored arrays or hash. The key is that the magnitude of powers of prime factors of a divisor should be equal to the minimum power of two prime factors of a and b.
- Find the prime factors of a using prime factorization.
- Find the count of each prime factor of a and store it in a Hashmap.
- Prime factorize b using distinct prime factors of a.
- Then the total number of divisors would be equal to the product of (count + 1)
of each factor. - count is the minimum of counts of each prime factors of a and b.
- This gives the count of all divisors of a and b.
C++
// C++ implementation of program
#include <bits/stdc++.h>
using namespace std;
// Map to store the count of each
// prime factor of a
map<int, int> ma;
// Function that calculate the count of
// each prime factor of a number
void primeFactorize(int a)
{
for(int i = 2; i * i <= a; i += 2)
{
int cnt = 0;
while (a % i == 0)
{
cnt++;
a /= i;
}
ma[i] = cnt;
}
if (a > 1)
{
ma[a] = 1;
}
}
// Function to calculate all common
// divisors of two given numbers
// a, b --> input integer numbers
int commDiv(int a, int b)
{
// Find count of each prime factor of a
primeFactorize(a);
// stores number of common divisors
int res = 1;
// Find the count of prime factors
// of b using distinct prime factors of a
for(auto m = ma.begin();
m != ma.end(); m++)
{
int cnt = 0;
int key = m->first;
int value = m->second;
while (b % key == 0)
{
b /= key;
cnt++;
}
// Prime factor of common divisor
// has minimum cnt of both a and b
res *= (min(cnt, value) + 1);
}
return res;
}
// Driver code
int main()
{
int a = 12, b = 24;
cout << commDiv(a, b) << endl;
return 0;
}
// This code is contributed by divyeshrabadiya07
Java
// Java implementation of program
import java.util.*;
import java.io.*;
class GFG {
// map to store the count of each prime factor of a
static HashMap<Integer, Integer> ma = new HashMap<>();
// method that calculate the count of
// each prime factor of a number
static void primeFactorize(int a)
{
for (int i = 2; i * i <= a; i += 2) {
int cnt = 0;
while (a % i == 0) {
cnt++;
a /= i;
}
ma.put(i, cnt);
}
if (a > 1)
ma.put(a, 1);
}
// method to calculate all common divisors
// of two given numbers
// a, b --> input integer numbers
static int commDiv(int a, int b)
{
// Find count of each prime factor of a
primeFactorize(a);
// stores number of common divisors
int res = 1;
// Find the count of prime factors of b using
// distinct prime factors of a
for (Map.Entry<Integer, Integer> m : ma.entrySet()) {
int cnt = 0;
int key = m.getKey();
int value = m.getValue();
while (b % key == 0) {
b /= key;
cnt++;
}
// prime factor of common divisor
// has minimum cnt of both a and b
res *= (Math.min(cnt, value) + 1);
}
return res;
}
// Driver method
public static void main(String args[])
{
int a = 12, b = 24;
System.out.println(commDiv(a, b));
}
}
Python3
# Python3 implementation of program
import math
# Map to store the count of each
# prime factor of a
ma = {}
# Function that calculate the count of
# each prime factor of a number
def primeFactorize(a):
sqt = int(math.sqrt(a))
for i in range(2, sqt, 2):
cnt = 0
while (a % i == 0):
cnt += 1
a /= i
ma[i] = cnt
if (a > 1):
ma[a] = 1
# Function to calculate all common
# divisors of two given numbers
# a, b --> input integer numbers
def commDiv(a, b):
# Find count of each prime factor of a
primeFactorize(a)
# stores number of common divisors
res = 1
# Find the count of prime factors
# of b using distinct prime factors of a
for key, value in ma.items():
cnt = 0
while (b % key == 0):
b /= key
cnt += 1
# Prime factor of common divisor
# has minimum cnt of both a and b
res *= (min(cnt, value) + 1)
return res
# Driver code
a = 12
b = 24
print(commDiv(a, b))
# This code is contributed by Stream_Cipher
C#
// C# implementation of program
using System;
using System.Collections.Generic;
class GFG{
// Map to store the count of each
// prime factor of a
static Dictionary<int,
int> ma = new Dictionary<int,
int>();
// Function that calculate the count of
// each prime factor of a number
static void primeFactorize(int a)
{
for(int i = 2; i * i <= a; i += 2)
{
int cnt = 0;
while (a % i == 0)
{
cnt++;
a /= i;
}
ma.Add(i, cnt);
}
if (a > 1)
ma.Add(a, 1);
}
// Function to calculate all common
// divisors of two given numbers
// a, b --> input integer numbers
static int commDiv(int a, int b)
{
// Find count of each prime factor of a
primeFactorize(a);
// Stores number of common divisors
int res = 1;
// Find the count of prime factors
// of b using distinct prime factors of a
foreach(KeyValuePair<int, int> m in ma)
{
int cnt = 0;
int key = m.Key;
int value = m.Value;
while (b % key == 0)
{
b /= key;
cnt++;
}
// Prime factor of common divisor
// has minimum cnt of both a and b
res *= (Math.Min(cnt, value) + 1);
}
return res;
}
// Driver code
static void Main()
{
int a = 12, b = 24;
Console.WriteLine(commDiv(a, b));
}
}
// This code is contributed by divyesh072019
JavaScript
<script>
// JavaScript implementation of program
// Map to store the count of each
// prime factor of a
let ma = new Map();
// Function that calculate the count of
// each prime factor of a number
function primeFactorize(a)
{
for(let i = 2; i * i <= a; i += 2)
{
let cnt = 0;
while (a % i == 0)
{
cnt++;
a = parseInt(a / i, 10);
}
ma.set(i, cnt);
}
if (a > 1)
{
ma.set(a, 1);
}
}
// Function to calculate all common
// divisors of two given numbers
// a, b --> input integer numbers
function commDiv(a,b)
{
// Find count of each prime factor of a
primeFactorize(a);
// stores number of common divisors
let res = 1;
// Find the count of prime factors
// of b using distinct prime factors of a
ma.forEach((values,keys)=>{
let cnt = 0;
let key = keys;
let value = values;
while (b % key == 0)
{
b = parseInt(b / key, 10);
cnt++;
}
// Prime factor of common divisor
// has minimum cnt of both a and b
res *= (Math.min(cnt, value) + 1);
})
return res;
}
// Driver code
let a = 12, b = 24;
document.write(commDiv(a, b));
</script>
Output:
6
Time Complexity: O(?n log n)
Auxiliary Space: O(n)
Efficient Solution -
A better solution is to calculate the greatest common divisor (gcd) of given two numbers, and then count divisors of that gcd.
C++
// C++ implementation of program
#include <bits/stdc++.h>
using namespace std;
// Function to calculate gcd of two numbers
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// Function to calculate all common divisors
// of two given numbers
// a, b --> input integer numbers
int commDiv(int a, int b)
{
// find gcd of a, b
int n = gcd(a, b);
// Count divisors of n.
int result = 0;
for (int i = 1; i <= sqrt(n); i++) {
// if 'i' is factor of n
if (n % i == 0) {
// check if divisors are equal
if (n / i == i)
result += 1;
else
result += 2;
}
}
return result;
}
// Driver program to run the case
int main()
{
int a = 12, b = 24;
cout << commDiv(a, b);
return 0;
}
Java
// Java implementation of program
class Test {
// method to calculate gcd of two numbers
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// method to calculate all common divisors
// of two given numbers
// a, b --> input integer numbers
static int commDiv(int a, int b)
{
// find gcd of a, b
int n = gcd(a, b);
// Count divisors of n.
int result = 0;
for (int i = 1; i <= Math.sqrt(n); i++) {
// if 'i' is factor of n
if (n % i == 0) {
// check if divisors are equal
if (n / i == i)
result += 1;
else
result += 2;
}
}
return result;
}
// Driver method
public static void main(String args[])
{
int a = 12, b = 24;
System.out.println(commDiv(a, b));
}
}
Python3
# Python implementation of program
from math import sqrt
# Function to calculate gcd of two numbers
def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
# Function to calculate all common divisors
# of two given numbers
# a, b --> input integer numbers
def commDiv(a, b):
# find GCD of a, b
n = gcd(a, b)
# Count divisors of n
result = 0
for i in range(1,int(sqrt(n))+1):
# if i is a factor of n
if n % i == 0:
# check if divisors are equal
if n/i == i:
result += 1
else:
result += 2
return result
# Driver program to run the case
if __name__ == "__main__":
a = 12
b = 24;
print(commDiv(a, b))
C#
// C# implementation of program
using System;
class GFG {
// method to calculate gcd
// of two numbers
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// method to calculate all
// common divisors of two
// given numbers a, b -->
// input integer numbers
static int commDiv(int a, int b)
{
// find gcd of a, b
int n = gcd(a, b);
// Count divisors of n.
int result = 0;
for (int i = 1; i <= Math.Sqrt(n); i++) {
// if 'i' is factor of n
if (n % i == 0) {
// check if divisors are equal
if (n / i == i)
result += 1;
else
result += 2;
}
}
return result;
}
// Driver method
public static void Main(String[] args)
{
int a = 12, b = 24;
Console.Write(commDiv(a, b));
}
}
// This code contributed by parashar.
PHP
<?php
// PHP implementation of program
// Function to calculate
// gcd of two numbers
function gcd($a, $b)
{
if ($a == 0)
return $b;
return gcd($b % $a, $a);
}
// Function to calculate all common
// divisors of two given numbers
// a, b --> input integer numbers
function commDiv($a, $b)
{
// find gcd of a, b
$n = gcd($a, $b);
// Count divisors of n.
$result = 0;
for ($i = 1; $i <= sqrt($n);
$i++)
{
// if 'i' is factor of n
if ($n % $i == 0)
{
// check if divisors
// are equal
if ($n / $i == $i)
$result += 1;
else
$result += 2;
}
}
return $result;
}
// Driver Code
$a = 12; $b = 24;
echo(commDiv($a, $b));
// This code is contributed by Ajit.
?>
JavaScript
<script>
// Javascript implementation of program
// Function to calculate gcd of two numbers
function gcd(a, b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// Function to calculate all common divisors
// of two given numbers
// a, b --> input integer numbers
function commDiv(a, b)
{
// find gcd of a, b
let n = gcd(a, b);
// Count divisors of n.
let result = 0;
for (let i = 1; i <= Math.sqrt(n); i++) {
// if 'i' is factor of n
if (n % i == 0) {
// check if divisors are equal
if (n / i == i)
result += 1;
else
result += 2;
}
}
return result;
}
let a = 12, b = 24;
document.write(commDiv(a, b));
</script>
Output :
6
Time complexity: O(n1/2) where n is the gcd of two numbers.
Auxiliary Space: O(1)
Another Approach:
1. Define a function "gcd" that takes two integers "a" and "b" and returns their greatest common divisor (GCD) using the Euclidean algorithm.
2. Define a function "count_common_divisors" that takes two integers "a" and "b" and counts the number of common divisors of "a" and "b" using their GCD.
3. Calculate the GCD of "a" and "b" using the "gcd" function.
4. Initialize a counter "count" to 0.
5. Loop through all possible divisors of the GCD of "a" and "b" from 1 to the square root of the GCD.
6. If the current divisor divides the GCD evenly, increment the counter by 2 (because both "a" and "b" are divisible by the divisor).
7. If the square of the current divisor equals the GCD, decrement the counter by 1 (because we've already counted this divisor once).
8. Return the final count of common divisors.
9. In the main function, define two integers "a" and "b" and call the "count_common_divisors" function with these integers.
10. Print the number of common divisors of "a" and "b" using the printf function.
C
#include <stdio.h>
int gcd(int a, int b) {
if(b == 0) {
return a;
}
return gcd(b, a % b);
}
int count_common_divisors(int a, int b) {
int gcd_ab = gcd(a, b);
int count = 0;
for(int i = 1; i * i <= gcd_ab; i++) {
if(gcd_ab % i == 0) {
count += 2;
if(i * i == gcd_ab) {
count--;
}
}
}
return count;
}
int main() {
int a = 12;
int b = 18;
int common_divisors = count_common_divisors(a, b);
printf("The number of common divisors of %d and %d is %d.\n", a, b, common_divisors);
return 0;
}
C++
#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) {
if(b == 0) {
return a;
}
return gcd(b, a % b);
}
int count_common_divisors(int a, int b) {
int gcd_ab = gcd(a, b);
int count = 0;
for(int i = 1; i * i <= gcd_ab; i++) {
if(gcd_ab % i == 0) {
count += 2;
if(i * i == gcd_ab) {
count--;
}
}
}
return count;
}
int main() {
int a = 12;
int b = 18;
int common_divisors = count_common_divisors(a, b);
cout<<"The number of common divisors of "<<a<<" and "<<b<<" is "<<common_divisors<<"."<<endl;
return 0;
}
Java
import java.util.*;
public class Main {
public static int gcd(int a, int b) {
if(b == 0) {
return a;
}
return gcd(b, a % b);
}
public static int countCommonDivisors(int a, int b) {
int gcd_ab = gcd(a, b);
int count = 0;
for(int i = 1; i * i <= gcd_ab; i++) {
if(gcd_ab % i == 0) {
count += 2;
if(i * i == gcd_ab) {
count--;
}
}
}
return count;
}
public static void main(String[] args) {
int a = 12;
int b = 18;
int commonDivisors = countCommonDivisors(a, b);
System.out.println("The number of common divisors of " + a + " and " + b + " is " + commonDivisors + ".");
}
}
Python3
import math
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
def count_common_divisors(a, b):
gcd_ab = gcd(a, b)
count = 0
for i in range(1, int(math.sqrt(gcd_ab)) + 1):
if gcd_ab % i == 0:
count += 2
if i * i == gcd_ab:
count -= 1
return count
a = 12
b = 18
common_divisors = count_common_divisors(a, b)
print("The number of common divisors of", a, "and", b, "is", common_divisors, ".")
# This code is contributed by Prajwal Kandekar
C#
using System;
public class MainClass
{
public static int GCD(int a, int b)
{
if (b == 0)
{
return a;
}
return GCD(b, a % b);
}
public static int CountCommonDivisors(int a, int b)
{
int gcd_ab = GCD(a, b);
int count = 0;
for (int i = 1; i * i <= gcd_ab; i++)
{
if (gcd_ab % i == 0)
{
count += 2;
if (i * i == gcd_ab)
{
count--;
}
}
}
return count;
}
public static void Main()
{
int a = 12;
int b = 18;
int commonDivisors = CountCommonDivisors(a, b);
Console.WriteLine("The number of common divisors of {0} and {1} is {2}.", a, b, commonDivisors);
}
}
JavaScript
// Function to calculate the greatest common divisor of
// two integers a and b using the Euclidean algorithm
function gcd(a, b) {
if(b === 0) {
return a;
}
return gcd(b, a % b);
}
// Function to count the number of common divisors of two integers a and b
function count_common_divisors(a, b) {
let gcd_ab = gcd(a, b);
let count = 0;
for(let i = 1; i * i <= gcd_ab; i++) {
if(gcd_ab % i === 0) {
count += 2;
if(i * i === gcd_ab) {
count--;
}
}
}
return count;
}
let a = 12;
let b = 18;
let common_divisors = count_common_divisors(a, b);
console.log(`The number of common divisors of ${a} and ${b} is ${common_divisors}.`);
OutputThe number of common divisors of 12 and 18 is 4.
The time complexity of the gcd() function is O(log(min(a, b))), as it uses Euclid's algorithm which takes logarithmic time with respect to the smaller of the two numbers.
The time complexity of the count_common_divisors() function is O(sqrt(gcd(a, b))), as it iterates up to the square root of the gcd of the two numbers.
The space complexity of both functions is O(1), as they only use a constant amount of memory regardless of the input size.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem