Syntax error GCD of an array of numbers in java

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: 2020-06-25T12:00:32+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements