Common Divisors of Two Numbers - GeeksforGeeks
Given two integer numbers, the task is to find count of all common divisors of given numbers?
Read full article from Common Divisors of Two Numbers - GeeksforGeeks
Given two integer numbers, the task is to find count of all common divisors of given numbers?
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.
A better solution is to calculate the greatest common divisor (gcd) of given two numbers, and then count divisors of that gcd.
// 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;
}