java - 求n个数的gcd

标签 java math greatest-common-divisor

这似乎是一个简单的问题,但我找不到解决方案。我必须找到n个数的gcd。

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

这是计算两个数字的gcd的流行递归方法。但如果我需要得到 3, 4, 5... n 个数字的 gcd 呢?我想做这样的事情:

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

有一个整数数组作为参数,但我不知道代码。您有什么建议吗?

最佳答案

多个数字的 GCD gcd( n1, n2, .... nx ) 可以通过增量计算两个数字的 GCD 来计算:

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

所有数字的每个除数都必须是这些数字的任何子集的除数。这又导出了上面的公式。

通过对两个数字重复使用给定的 getGCD(int, int) 函数,我们可以创建一个额外的重载,该重载采用一个或多个数字的列表:

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

关于java - 求n个数的gcd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25890293/

相关文章:

math - float 学有问题吗?

java - 如果递归调用应该在 a 或 b 变为 0 时停止并返回,为什么这个最大公约数程序的输出为 -1

c++ - 意外的浮点异常 - C++

arrays - 从数组计算最大公约数的有效方法 - Swift

java - Java中如何设置if-else来解析数组元素

java - 如何制作我的 jar 的可分发批处理文件

C++ 优化这个算法

带有十进制数字的javascript数学

java - 我如何打印元音以及它们是什么?

java - 通过 Rest 的 Cypher 请求返回 400 Bad Request,为什么?