1. 程式人生 > 實用技巧 >快速求冪模運算實現

快速求冪模運算實現

就是求:

參考自:
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程式碼:

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

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