从一组2个以上整数最大公约数 [英] Greatest Common Divisor from a set of more than 2 integers

查看:124
本文介绍了从一组2个以上整数最大公约数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有堆栈溢出几个问题讨论如何找到两个值的最大公约数。一个很好的回答显示出整齐的 递归函数 做到这一点。

但我怎么能找到一套超过2个整数的GCD?我似乎无法找到这样的一个例子。


任何人都可以提出最有效的code来实现这个功能呢?

 静态INT GCD(INT [] IntegerSet)
{
    //发生的事情吗?
}
 

解决方案

在这里,你必须使用LINQ和GCD的方法从你链接的问题code例子。它是利用在其他的答案中描述的理论算法... GCD(A,B,C)= GCD(GCD(A,B),C)

 静态INT GCD(INT []号)
{
    返回numbers.Aggregate(GCD);
}

静态INT GCD(INT A,INT B)
{
    返回b == 0?答:GCD(B,A%B);
}
 

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

解决方案

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

这篇关于从一组2个以上整数最大公约数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆