快速求幂模运算实现

就是求:

参考自:
1: https://www.rookieslab.com/posts/fast-power-algorithm-exponentiation-by-squaring-cpp-python-implementation#brute-force-python-implementation
2: https://blog.csdn.net/qq_19782019/article/details/85621386

Python代码实现方法1:

def fast_power(base, power, MOD):
    """
    Returns the result of a^b i.e. a**b
    We assume that a >= 1 and b >= 0

    Remember two things!
     - Divide power by 2 and multiply base to itself (if the power is even)
     - Decrement power by 1 to make it even and then follow the first step
    """

    result = 1
    while power > 0:
        # If power is odd
        if power % 2 == 1:
            result = (result * base) % MOD

        # Divide the power by 2
        power = power // 2
        # Multiply base to itself
        base = (base * base) % MOD

    return result

另一种实现方法:

def fast_power2(a, b, n, show = True):
    c,f = 0,1
    k = len(bin(b)) - 3
    binstr = bin(b)[2:][::-1]
    if show:
        print("i | b_i    c       d ")
        print("----------------------")
    for i in range(k, -1, -1):
        c = 2*c
        f = pow(f, 2) % n
        if binstr[i] == '1':
            c += 1
            f = (f * a) % n
        if show:
            print("{} | {:^2}   {:^5}   {:^5}".format(i, binstr[i], c, f))
    return f

C语言实现:

typedef long long LL;

LL FastPowerMod( LL base, LL power , LL N )
{
    LL  res = 1;
    base = base % N;
    while(power > 0){
        if(power & 1)
            res = (res * base) % N;
        base = (base * base) % N;
        power >>= 1;
    }
    return res;
}
posted @ 2020-11-02 10:45  爱吃砂糖橘的白龙  阅读(237)  评论(0编辑  收藏  举报