2

This could seem an easy question but I cannot find a solution. I must find the gcd of n numbers.

public int getGCD(int a, int b) {
 if (b == 0) { return a; }
 else { return getGCD(b, a%b); }
}

This is the popular recursive way that calculates the gcd of two numbers. But if I need to get the gcd of 3, 4, 5... n numbers? I was thinking to do something like this:

public int getGCD(int[] a) {
 //the code  
}

There is an array of integer as parameter, but I have no idea about the code. Do you have any suggestion?

Arnab Nandy
  • 6,472
  • 5
  • 44
  • 50
Alberto Miola
  • 4,643
  • 8
  • 35
  • 49
  • take a look at here http://stackoverflow.com/questions/15351195/finding-the-gcd-of-n-numbers – Key_coder Sep 17 '14 at 12:16
  • The question is apparently a duplicate of this question http://stackoverflow.com/questions/1231733/euclidian-greatest-common-divisor-for-more-than-two-numbers – Codor Sep 17 '14 at 12:16

4 Answers4

10

The GCD of a multiple numbers gcd( n1, n2, .... nx ) can be computed by incrementally computing the GCD of two numbers:

gcd( n1, n2, .... nx ) == gcd( n1, gcd( n2, gcd( ... , nx ) ) )

Every divisor for all numbers, has to be a divisor for any subset of these numbers. Which in turn leads to the above formula.

By reusing your given getGCD(int, int) function for two numbers, we can create an additional overload that takes a list of one or more numbers:

public int getGCD(int a, int b) {
 // implementation for two numbers goes here
}

public int getGCD(int[] a) {
  // the GCD of a number with itself is... itself
  int gcd = a[0];

  // compute incrementally
  for( int i=1; i<a.length; i++ ) {
    gcd = getGCD( gcd, a[i] );
  }

  // return result
  return gcd;    
}
Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
Sirko
  • 72,589
  • 19
  • 149
  • 183
  • note that the original function and the new function are now named the same. Change the original to sth. else.. – Wampie Driessen Sep 17 '14 at 12:20
  • 1
    The function takes an int[] and you're passing two int values. Is it correct? – Alberto Miola Sep 17 '14 at 12:21
  • 1
    @WampieDriessen stop nit-picking. An OP should be able to follow from this sort of ***example***. – UmNyobe Sep 17 '14 at 12:22
  • 1
    @DK64 Added your function and renamed mine, to make it more obvious which function is which. – Sirko Sep 17 '14 at 12:24
  • 1
    @Sirko In Java, it was better using the overloaded method names. – Sam Harwell Sep 17 '14 at 12:25
  • @280Z28 But obviously it lead to some confusion for OP here. In general, though, I agree (see the first version of the function). – Sirko Sep 17 '14 at 12:37
  • @Sirko I cleaned up the wording. Also I remove the implementation details for two numbers since the algorithm it used was not particularly desirable and I didn't want it to detract from the rest of your answer. – Sam Harwell Sep 17 '14 at 12:42
7

Try with this,

public static void main(String[] args) {
    System.out.println(" GDC: " + getGdc(12, 48, 24, 5));
    System.out.println(" GDC: " + getGdc(12, 48, 24));
}

public static int getGdc(int... x) {
    // get the smallest of all number no need to check for higher values
    int smallest = getSmallest(x);

    for(int i = smallest; i >= 1; i--) {
       int j;
       for(j = 0; j < x.length; ++j) {
           if(x[j] % i != 0)
               break;
       }
       // if we pass through the array with all % == 0 return the value
       if(j == x.length)
           return i;
    }
    // so the only possible is 1
    return 1;
}

// return smallest number of an array of int
public static int getSmallest(int[] x) {
    int smallest = x[0];
    for(int i = 1; i < x.length; ++i) {
        if(x[i] < smallest)
            smallest = x[i];
    }
    return smallest;
}

Refer this also for more. Hope this helps

codebot
  • 2,540
  • 3
  • 38
  • 89
3

Java’s latest features can come in handy here. The idea is that we take the first two numbers from a, find their gcd, and put that back in a. This is exactly what a reduce operation does (although I’ll use the reduce for an intStream).

You then have:

public int getGCD(int[] a) {
    Arrays.stream(a).reduce( (b,c) -> getGCD(b,c) ).getAsInt();
}

You may be able to replace the lambda expression with a method reference:

    Arrays.stream(a).reduce(ClassName::getGCD).getAsInt();

(Although I’m assuming the compiler will know you’re referring to getGCD(int,int). If it complains, you’d have to rename a method.)

Teepeemm
  • 4,331
  • 5
  • 35
  • 58
0
package may23;
/**
 * 
 * @author Ramkumar Raja
 *
 */
public class GcdofArrayNumbers {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int arr[]={8,16,80};
        int temp=0;
        for(int i =0;i<arr.length;i++)
        {
            if(i==0)
            {
                temp=gcdArray(arr[i+1], arr[i]);
                i++;
            }
            else
            {
                temp=gcdArray(temp, arr[i]);
            }
        }
        System.out.println("Gcd"+temp);


    }

    public static int gcdArray(int a,int b)
    {
        int gcd=0;
        for(int i=1;i<=a && i<=b;i++)
        {
            if(a%i==0 && b%i==0)
            {
                gcd=i;
            }

        }

        return gcd;

    }

}
Kohei TAMURA
  • 4,970
  • 7
  • 25
  • 49
ram kumar
  • 379
  • 3
  • 5