Java Program for Common Divisors of Two Numbers

JavaObject Oriented ProgrammingProgramming

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.

raja
Published on 04-Jul-2020 09:51:53
Advertisements