Java Program for GCD of more than two (or array) numbers


Following is the Java program for GCD of more than two numbers −

Example

 Live Demo

public class Demo{
   static int gcd_of_nums(int val_1, int val_2){
      if (val_1 == 0)
      return val_2;
      return gcd_of_nums(val_2 % val_1, val_1);
   }
   static int find_gcd(int arr[], int no){
      int result = arr[0];
      for (int i = 1; i < no; i++){
         result = gcd_of_nums(arr[i], result);
         if(result == 1){
            return 1;
         }
      }
      return result;
   }
   public static void main(String[] args){
      int my_arr[] = { 7, 49, 177, 105, 119, 42};
      int no = my_arr.length;
      System.out.println("The GCD of the elements in the array is ");
      System.out.println(find_gcd(my_arr, no));
   }
}

Output

The GCD of the elements in the array is
1

A class named Demo contains a main function that takes in two values. If the first value is 0, the second value is returned as output. Otherwise, a recursive function is written that computes the greatest common divisor of the two elements.

Next, another static function is defined that takes an array and another integer value as parameter. The first element of the array is assigned to a variable named ‘result’ and a ‘for’ loop iterates over elements from 1 to the integer value that was passed as a parameter to the function. The greatest common divisor function is called on this array elements and a result. This output is assigned to ‘result’ variable itself. If the value of ‘result’ is 1, then the output is 1, otherwise the value of ‘result’ is returned.

In the main function, an array integer is defined and the length of the array is assigned to a specific value. The greatest common divisor function is called on the array elements and length. Relevant data is displayed on the console.

Updated on: 04-Jul-2020

388 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements