- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Java Program for Common Divisors of Two Numbers

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

## Example

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.

- Related Questions & Answers
- C++ Program for Common Divisors of Two Numbers?
- Python 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
- Java Program for Longest Common Subsequence
- Print the kth common factor of two numbers
- Java Program for GCD of more than two (or array) numbers
- Check if sum of divisors of two numbers are same in Python
- Count common prime factors of two numbers in C++
- Write a program to calculate the least common multiple of two numbers JavaScript
- Java Program to Find GCD of two Numbers
- Java Program to Find LCM of two Numbers
- Java Program to Add Two Numbers
- Java Program to Swap Two Numbers.