GCD of an array of numbers in java

Java Programming Java8Java.Util Package

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
raja
Published on 04-Jun-2018 11:52:28
Advertisements