What is the fastest way to compute large power of 2 modulo a number

前端 未结 5 2162
南方客
南方客 2020-12-06 02:48

For 1 <= N <= 1000000000, I need to compute 2N mod 1000000007, and it must be really fast!
My current approach i

5条回答
  •  无人及你
    2020-12-06 03:30

    This method doesn't use recursion with O(log(n)) complexity. Check this out.

    #define ull unsigned long long
    #define MODULO 1000000007
    
    ull PowMod(ull n)
    {
        ull ret = 1;
        ull a = 2;
        while (n > 0) {
            if (n & 1) ret = ret * a % MODULO;
            a = a * a % MODULO;
            n >>= 1;
        }
        return ret;
    }
    

    And this is pseudo from Wikipedia (see Right-to-left binary method section)

    function modular_pow(base, exponent, modulus)
    Assert :: (modulus - 1) * (base mod modulus) does not overflow base
    result := 1
    base := base mod modulus
    while exponent > 0
        if (exponent mod 2 == 1):
           result := (result * base) mod modulus
        exponent := exponent >> 1
        base := (base * base) mod modulus
    return result
    

提交回复
热议问题