Java Program for Common Divisors of Two Numbers
Last Updated :
09 Sep, 2022
Given two integer numbers, the task is to find the count of all common divisors of given numbers?
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
Java
class Test {
static int gcd( int a, int b)
{
if (a == 0 )
return b;
return gcd(b % a, a);
}
static int commDiv( int a, int b)
{
int n = gcd(a, b);
int result = 0 ;
for ( int i = 1 ; i <= Math.sqrt(n); i++) {
if (n % i == 0 ) {
if (n / i == i)
result += 1 ;
else
result += 2 ;
}
}
return result;
}
public static void main(String args[])
{
int a = 12 , b = 24 ;
System.out.println(commDiv(a, b));
}
}
|
Time complexity: O(sqrt(n)) because for loop will run for sqrt(n) times and function to calculate gcd will take O(log(min(a,b))
Auxiliary Space: O(log(min(a,b)) due to recursive stack space
Please refer complete article on Common Divisors of Two Numbers for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...