Search code examples
pythonmathmodularmodular-arithmetic

How to calculate 2 to the power of a large number modulo another large number?


M = 115792089237316195423570985008687907853269984665640564039457584007908834671663

296514807760119017459957299373576180339312098253841362800539826362414936958669 % M = ?

Is it possible to calculate this in Python? Or are there other methods?


Solution

  • To calculate the result, the three-argument pow does this efficiently, as mentioned by @MarkDickinson in the comments.

    A simplified explanation of how this works:

    • to calculate 2**N mod M, first find K = 2**(N//2) mod M
    • if N was even, 2**N mod M = K * K mod M
    • if N was odd, 2**N mod M = K * K * 2 mod M That way, there is no need to calculate huge numbers. In reality, pow uses more tricks, is more general and doesn't need recursion.

    Here is some demonstration code:

    def pow_mod(B, E, M):
        if E == 0:
            return 1
        elif E == 1:
            return B % M
        else:
            root = pow_mod(B, E // 2, M)
            if E % 2 == 0:
                return (root * root) % M
            else:
                return (root * root * B) % M
    
    M = 115792089237316195423570985008687907853269984665640564039457584007908834671663
    E = 96514807760119017459957299373576180339312098253841362800539826362414936958669
    
    print(pow_mod(2, E, M))
    print(pow(2, E, M))