一组超过2个整数的最大公约数

时间:2010-09-03 12:12:37

标签: c# algorithm math

Stack Overflow上有几个问题讨论如何找到两个值的最大公约数。一个好的答案显示了一个整洁的 recursive function 来做到这一点。

但是如何找到一组超过2个整数的GCD?我似乎无法找到这样的例子。


有人能建议最有效的代码来实现这个功能吗?

static int GCD(int[] IntegerSet)
{
    // what goes here?
}

13 个答案:

答案 0 :(得分:46)

这里有代码示例使用LINQ和GCD方法来解决您的问题。它使用的是其他答案中描述的理论算法...... 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);
}

答案 1 :(得分:13)

你可以使用GCD的这个共同属性:

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

假设您已定义GCD(a, 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);
    }    
}

答案 2 :(得分:4)

这是C#版本。

  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;
  }

}

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

答案 3 :(得分:3)

Wikipedia

  

gcd是一个关联函数:   gcd(a,gcd(b,c))= gcd(gcd(a,b),c)。

     

三个数字的gcd可以计算为gcd(a,b,c)= gcd(gcd(a,b),c),或者某些   应用交换性和相关性的不同方式。这可以扩展到任意数量的数字。

只需取前两个元素的gcd,然后计算结果的gcd和第三个元素,然后计算结果的gcd和第四个元素......

答案 4 :(得分:2)

将其重写为单一功能......

    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);
    } 

答案 5 :(得分:1)

gcd(a1,a2,...,an)=gcd(a1,gcd(a2,gcd(a3...(gcd(a(n-1),an))))),如果某些gcd评估为1,我会逐步中止。

如果你的数组已经排序,那么之前评估gcd的小数字可能会更快,因为那时一个gcd评估为1的可能性更大,你可以停止。

答案 6 :(得分: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]);
    }
}

答案 7 :(得分: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

答案 8 :(得分:0)

这是最常用的三种:

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);
    }
  }

答案 9 :(得分:0)

不使用LINQ。

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

    static int GCD(params int[] numbers)
    {
        int gcd = 0;
        int a = numbers[0];
        for(int i = 1; i < numbers.Length; i++)
        {
            gcd = GCD(a, numbers[i]);
            a = numbers[i];
        }

        return gcd;
    }

答案 10 :(得分: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))

答案 11 :(得分:0)

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

enter code here

公共类Program {静态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); }

答案 12 :(得分:0)

使用此方法,您还可以以数组的形式传递多个值:-

// 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); 
    }