tags:

views:

211

answers:

5

There are several questions on Stack Overflow discussing how to find the Greatest Common Divisor of two values. One good answer shows a neat recursive function to do this.

But how can I find the GCD of a set of more than 2 integers? I can't seem to find an example of this.


Can anyone suggest the most efficient code to implement this function?

static int GCD(int[] IntegerSet)
{
    // what goes here?
}
+1  A: 

Wikipedia:

The gcd is an associative function: gcd(a, gcd(b, c)) = gcd(gcd(a, b), c).

The gcd of three numbers can be computed as gcd(a, b, c) = gcd(gcd(a, b), c), or in some different way by applying commutativity and associativity. This can be extended to any number of numbers.

Just take the gcd of the first two elements, then calculate the gcd of the result and the third element, then calculate the gcd of the result and fourth element...

Landei
+1  A: 

Here's the C# version.

  public static int Gcd(int[] x) {
      if (x.length < 2) {
          throw new ArgumentException("Do not use this method if there are less than two numbers.");
      }
      int tmp = Gcd(x[x.length - 1], x[x.length - 2]);
      for (int i = x.length - 3; i >= 0; i--) {
          if (x[i] < 0) {
              throw new ArgumentException("Cannot compute the least common multiple of several numbers where one, at least, is negative.");
          }
          tmp = Gcd(tmp, x[i]);
      }
      return tmp;
  }

  public static int Gcd(int x1, int x2) {
      if (x1 < 0 || x2 < 0) {
          throw new ArgumentException("Cannot compute the GCD if one integer is negative.");
      }
      int a, b, g, z;

      if (x1 > x2) {
          a = x1;
          b = x2;
      } else {
          a = x2;
          b = x1;
      }

      if (b == 0) return 0;

      g = b;
      while (g != 0) {
          z= a % g;
          a = g;
          g = z;
      }
      return a;
  }

}

Source http://www.java2s.com/Tutorial/Java/0120__Development/GreatestCommonDivisorGCDofpositiveintegernumbers.htm

randomguy
I was just about to mention that you'd missed out the second function... but you fixed it :) Thanks, this is exactly what I need.
BG100
I was about to accept your answer, but Darin Dimitrov and Matajon have come up with a neater method. Sorry! (+1 anyway)
BG100
Sorry about that. I was too hasty thinking I'm the only one with the right answer. ;) If speed is important, this method should be tested against the LINQ methods described by Darin and Matajon. If not, I'm more than happy to say that you should use the LINQ method as it is much more elegant.
randomguy
+6  A: 

You could use this common property of a GCD:

GCD(a, b, c) = GCD(a, GCD(b, c)) = GCD(GCD(a, b), c) = GCD(GCD(a, c), b)

Assuming you have GCD(a, b) already defined it is easy to generalize:

public class Program
{
    static void Main()
    {
        Console.WriteLine(GCD(new[] { 10, 15, 30, 45 }));
    }

    static int GCD(int a, int b)
    {
        return b == 0 ? a : GCD(b, a % b);
    }

    static int GCD(int[] integerSet)
    {
        return integerSet.Aggregate(GCD);
    }    
}
Darin Dimitrov
Thanks, exactly what I need, but your edit came slightly too late, Matajon came up with the same answer just before you... So I think it's only fair for me to accept his. (+1 anyway)
BG100
+1  A: 

gcd(a1,a2,...,an)=gcd(a1,gcd(a2,gcd(a3...(gcd(a(n-1),an))))), so I would do it just step by step aborting if some gcd evaluates to 1.

If your array is sorted, it might be faster to evaluate gcd for small numbers earlier, since then it might be more likely that one gcd evaluates to 1 and you can stop.

phimuemue
+7  A: 

And here you have code example using LINQ and GCD method from question you linked. It is using theoretical algorithm described in other answers ... GCD(a, b, c) = GCD(GCD(a, b), c)

static int GCD(int[] numbers)
{
    return numbers.Aggregate(GCD);
}

static int GCD(int a, int b)
{
    return b == 0 ? a : GCD(b, a % b);
}
Matajon
Perfect, thanks. Just what I'm looking for!
BG100