18

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?
}
Community
  • 1
  • 1
BG100
  • 4,481
  • 2
  • 37
  • 64
  • 5
    GCD is associative and commutative like + and *, so you can successively apply GCD to the numbers in any order. – starblue Sep 03 '10 at 17:04
  • 1
    if C# has the "inject" or "reduce" method for lists, like many functional languages do, then this is a snap. – Justin L. Sep 03 '10 at 17:46

12 Answers12

52

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);
}
BlueRaja - Danny Pflughoeft
  • 84,206
  • 33
  • 197
  • 283
Martin Jonáš
  • 2,309
  • 15
  • 12
  • 1
    A minor upspeed: `return b == 0 ? a : GCD(Math.Min(a,b), Math.Max(a,b) % Math.Min(a,b));` This saves up to 50% of the `%` divisions when `numbers[]` contains ascending values. – robert4 Apr 30 '14 at 12:46
  • 1
    @robert4 - Your solution gets divide by zero errors. Need to add a check for `a == 0` as well. `return b == 0 ? a : (a == 0 ? b : GCD(Math.Min(a,b), Math.Max(a,b) % Math.Min(a,b)));` – NightOwl888 Oct 15 '16 at 21:33
  • 1
    @NightOwl888 You have a point. `return (a == 0 || b == 0) ? a|b : GCD(Math.Min(a, b), Math.Max(a, b) % Math.Min(a, b));` – robert4 Nov 16 '16 at 13:20
13

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
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 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 Sep 03 '10 at 12:34
3

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
  • 54,104
  • 13
  • 100
  • 195
3

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
  • 12,042
  • 16
  • 71
  • 101
  • 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 Sep 03 '10 at 12:23
  • I was about to accept your answer, but Darin Dimitrov and Matajon have come up with a neater method. Sorry! (+1 anyway) – BG100 Sep 03 '10 at 12:31
  • 1
    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 Sep 03 '10 at 12:32
2

Rewriting this as a single function...

    static int GCD(params int[] numbers)
    {
        Func<int, int, int> gcd = null;
        gcd = (a, b) => (b == 0 ? a : gcd(b, a % b));
        return numbers.Aggregate(gcd);
    } 
1
int GCD(int a,int b){ 
    return (!b) ? (a) : GCD(b, a%b);
}

void calc(a){
    int gcd = a[0];
    for(int i = 1 ; i < n;i++){
        if(gcd == 1){
            break;
        }
        gcd = GCD(gcd,a[i]);
    }
}
hon2a
  • 7,006
  • 5
  • 41
  • 55
Jitendra
  • 52
  • 8
1

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
  • 34,669
  • 9
  • 84
  • 115
0
/*

Copyright (c) 2011, Louis-Philippe Lessard
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

unsigned gcd ( unsigned a, unsigned b );
unsigned gcd_arr(unsigned * n, unsigned size);

int main()
{
    unsigned test1[] = {8, 9, 12, 13, 39, 7, 16, 24, 26, 15};
    unsigned test2[] = {2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048};
    unsigned result;

    result = gcd_arr(test1, sizeof(test1) / sizeof(test1[0]));
    result = gcd_arr(test2, sizeof(test2) / sizeof(test2[0]));

    return result;
}


/**
* Find the greatest common divisor of 2 numbers
* See http://en.wikipedia.org/wiki/Greatest_common_divisor
*
* @param[in] a First number
* @param[in] b Second number
* @return greatest common divisor
*/
unsigned gcd ( unsigned a, unsigned b )
{
    unsigned c;
    while ( a != 0 )
    {
        c = a;
        a = b%a;
        b = c;
    }
    return b;
}

/**
* Find the greatest common divisor of an array of numbers
* See http://en.wikipedia.org/wiki/Greatest_common_divisor
*
* @param[in] n Pointer to an array of number
* @param[in] size Size of the array
* @return greatest common divisor
*/
unsigned gcd_arr(unsigned * n, unsigned size)
{
    unsigned last_gcd, i;
    if(size < 2) return 0;

    last_gcd = gcd(n[0], n[1]);

    for(i=2; i < size; i++)
    {
        last_gcd = gcd(last_gcd, n[i]);
    }

    return last_gcd;
}

Source code reference

yayay
  • 260
  • 2
  • 5
0

These are the three most common used:

    public static uint FindGCDModulus(uint value1, uint value2)
    {
        while(value1 != 0 && value2 != 0) {
            if (value1 > value2) {
                value1 %= value2;
            } else {
                value2 %= value1;
            }
        }
        return Math.Max(value1, value2);
    }
    public static uint FindGCDEuclid(uint value1, uint value2)
    {
        while(value1 != 0 && value2 != 0) {
            if (value1 > value2) {
                    value1 -= value2;
            } else {
                    value2 -= value1;
            }
        }
        return Math.Max(value1, value2);
    }
    public static uint FindGCDStein(uint value1, uint value2)
    {
        if (value1 == 0) return value2;
        if (value2 == 0) return value1;
        if (value1 == value2) return value1;

        bool value1IsEven = (value1 & 1u) == 0;
        bool value2IsEven = (value2 & 1u) == 0;
                       
        if (value1IsEven && value2IsEven) {
            return FindGCDStein(value1 >> 1, value2 >> 1) << 1;
        } else if (value1IsEven && !value2IsEven) {
            return FindGCDStein(value1 >> 1, value2);
        } else if (value2IsEven) {
            return FindGCDStein(value1, value2 >> 1);
        } else if (value1 > value2) {
            return FindGCDStein((value1 - value2) >> 1, value2);
        } else {
            return FindGCDStein(value1, (value2 - value1) >> 1);
        }
    }
greybeard
  • 2,249
  • 8
  • 30
  • 66
chikito1990
  • 229
  • 1
  • 4
  • 13
0
let a = 3
let b = 9

func gcd(a:Int, b:Int) -> Int {
    if a == b {
        return a
    }
    else {
        if a > b {
            return gcd(a:a-b,b:b)
        }
        else {
            return gcd(a:a,b:b-a)
        }
    }
}
print(gcd(a:a, b:b))
EstevaoLuis
  • 2,422
  • 7
  • 33
  • 40
0

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

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);
  }
}
Christopher Allen
  • 7,769
  • 5
  • 20
  • 35
0

By using this, you can pass multiple values as well in the form of array:-

// pass all the values in array and call findGCD function
    int findGCD(int arr[], int n) 
    { 
        int gcd = arr[0]; 
        for (int i = 1; i < n; i++) {
            gcd = getGcd(arr[i], gcd); 
        }

        return gcd; 
    } 

// check for gcd
    int getGcd(int x, int y) 
    { 
        if (x == 0) 
            return y; 
        return gcd(y % x, x); 
    } 
greybeard
  • 2,249
  • 8
  • 30
  • 66
Chang
  • 435
  • 1
  • 8
  • 17