除法與GCD演算法的相關分析

weixin_34239169發表於2018-05-17

學習演算法三個要素:

1、驗證演算法的正確性
2、分析演算法的效率
3、如何提高演算法的效率

以下是兩個算除法的“玩具”演算法,請驗證其正確性,分析它們的效率並進行對比,並思考是否可以進一步提高除法的效率。最後這個問題不容易。

def QuoRem(a, b):
    q, r = 0, 0
    while(a >= b):
        a, q = a - b, q + 1
    r = a
    return q, r

def BinaryQuoRem(a, b):
    if(a == 0):
        return 0, 0
    q, r = BinaryQuoRem(a // 2, b)
    q, r = 2 * q, 2 * r
    if(a & 1): #if a is an odd number
        r = r + 1
    if(r >= b):
        r, q = r - b, q + 1
    return q, r

GCD 與Binary GCD的對比

為什麼需要Binary GCD?
為什麼看上去Binary GCD更高效?
但是,Binary GCD真的更高效嗎?為什麼是,為什麼不是?
請分析下面這兩個演算法,並回答以上問題。

# Function to implement Euclidean Algorithm
def gcd(a, b):
    while(b):
        a, b = b, a % b
    return a

# Function to implement Stein's Algorithm
def binary_gcd( a, b) :

    # GCD(0, b) == b; GCD(a, 0) == a,
    # GCD(0, 0) == 0
    if (a == 0) :
        return b

    if (b == 0) :
        return a

    # Finding K, where K is the greatest
    # power of 2 that divides both a and b.
    k = 0

    while(((a | b) & 1) == 0) :
        a = a >> 1
        b = b >> 1
        k = k + 1

    # Dividing a by 2 until a becomes odd
    while ((a & 1) == 0) :
        a = a >> 1

    # From here on, 'a' is always odd.
    while(b != 0) :

        # If b is even, remove all factor of
        # 2 in b
        while ((b & 1) == 0) :
            b = b >> 1

        # Now a and b are both odd. Swap if
        # necessary so a <= b, then set
        # b = b - a (which is even).
        if (a > b) :

            # Swap u and v.
            a, b = b, a

        b = (b - a)

    # restore common factors of 2
    return (a << k)

總結

演算法分析實在是太難了!

參考文獻

1、對Binary GCD的分析
2、Recursive Binary GCD
3、快速乘法及其應用


2018.0518

相關文章