Greatest Common Divisor or Highest Common Factor

Math

Write an algorithm to determine the GCD of N positive numbers.

Analysis & Solution

欧几里得算法求最大公约数

关于GCD算法,自然是有欧几里得算法Euclid Algorithm。不过实现上,可以是迭代,或者递归。

Pseudo Code:

Iterative

function gcd(a, b)
    while b ≠ 0
        t ← b
        b ← a mod b
        a ← t
    return a

Recursive:

function gcd(a, b)
    if b = 0
       return a
    else
       return gcd(b, a mod b)

Iterative (Java)

Recursive (Java)

Euclid Algorithm Time Complexity

这是一个挺复杂的数学问题,作为估计(也是实际上的),可以认为迭代次数O(logN)

如何从两个数的GCD拓展到N个数呢?

You could use this common property of a GCD:

GeeksforGeeks:

For an array of elements:

Implementation:

Reference

Greatest Common Divisor of a list of numbers - C++ and Python Implementation https://www.rookieslab.com/posts/cpp-python-code-to-find-gcd-of-a-list-of-numbers

https://www.geeksforgeeks.org/gcd-two-array-numbers/

Time complexity of Euclid's Algorithm https://stackoverflow.com/questions/3980416/time-complexity-of-euclids-algorithm

欧几里得算法时间复杂度简单分析 https://blog.csdn.net/ZeroOnet/article/details/53375313

Last updated

Was this helpful?