# Java Program for Common Divisors of Two Numbers

JavaObject Oriented ProgrammingProgramming

#### Complete Java Programming Fundamentals With Sample Projects

98 Lectures 7.5 hours

#### Get your Java dream job! Beginners interview preparation

85 Lectures 6 hours

#### Core Java bootcamp program with Hands on practice

Featured

99 Lectures 17 hours

Following is an example for Common Divisors of Two numbers in Java −

## Example

Live Demo

public class Demo{
static int find_gcd(int val_1, int val_2){
if (val_1 == 0)
return val_2;
return find_gcd(val_2%val_1,val_1);
}
static int common_divisors(int val_1,int val_2){
int no = find_gcd(val_1, val_2);
int result = 0;
for (int i=1; i<=Math.sqrt(no); i++){
if (no%i==0){
if (no/i == i)
result += 1;
else
result += 2;
}
}
return result;
}
public static void main(String args[]){
int val_1 = 68, val_2 = 34;
System.out.println("The common divisors between the two numbers is ");
System.out.println(common_divisors(val_1, val_2));
}
}

## Output

The common divisors between the two numbers is
4

A class named Demo contains a static function that takes two values and returns the greatest common divisor using recursion. Another function calls this greatest common divisor function and iterates through numbers between 1 and square root of the greatest common divisor.

Next, the condition is that the number modulus of the values iterated should be equal to zero and next, the number divided by the values iterated should be equal to the value iterated, then the result (which was initialized to 0 initially) is incremented by 1. If the condition is not satisfied, then the result is incremented by 2. In the main function, two values are initialized, and the above function is called on it. Relevant result is displayed on the screen.