快速最大公约数 (GCD) 算法
欧几里得算法的计算效率远高于其他方法
我不推荐方案 2,原因如下
1. 最重要的是,我的解决方案核心的欧几里得算法的计算效率(见下文 - 原始,推荐)明显高于方案 1 中实现的简单迭代(本质上是从较小的数开始向下循环并检查两个变量的可除性)(见下文)。
// fast Euclid GCD algorithm for 2 integers: RECOMMENDED if (list.Length == 2) { Int64 a = list[0]; Int64 b = list[1]; while (b != 0) { GCD = b; b = a % b; a = GCD; } return GCD;
供参考:根据一般理论,欧几里得算法完成所需的步骤数不应超过最小数字(十进制)的位数(基数 10)的 5 倍。 甚至存在比这种经典的欧几里得算法更高效的算法,但它们也相应地更加复杂。
注意:由于效率低下,不推荐以下算法(关于方案 2)
//Find the larger of the two numbers, the GCD can not be more than half of the smaller number. max = value1 > value2 ? (value2 / 2) : (value1 / 2); counter = max + 1; while ((!gcdFound) && (counter > 1)) { counter--; gcdFound = ((value1 % counter) == 0) && ((value2 % counter) == 0); }
2. 在我的原始算法中实现的传递数组和相应的数组操作对于将其扩展到不仅仅是两个输入变量至关重要。 无需重写我的函数,因为可以简单地为仅 2 个变量对其进行重载(只需添加第二个函数,接受 2 个参数并调用原始函数),或者可以通过像下面示例中那样简单地传递变量值 value1 和 value2 来实现相同的结果。
Int64 _gcd = GCD(new Int64[] {value1, value2 });
希望我已回答了您的问题。
此致,
亚历山大·贝尔