GCD of an array of numbers in java


Program

Following is the example to calculate the GCD of the numbers of an array.

Live Demo

public class GCDOfArrayofNumbers{
   public static int gcd(int a,int b){
      int res = 0;
      while (b > 0){
         int temp = b;
         b = a % b;
         a = temp;
         res = a;
      }
      return res;
   }
   public static void main(String arg[]){
      int[] myArray = {3, 6, 8};
      int result = gcd(myArray[0],myArray[1]);
      for(int i = 2; i < myArray.length; i++){
         result = gcd(result, myArray[i]);
      }
      System.out.println("Gcd of n numbers is: "+result);
   }
}

Output

GCD of n numbers is: 1

Updated on: 25-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements