Quick power detailed explanation with video

Everyone understands that the premise of this kind of algorithm must have a little foundation for bitwise operations, and at the same time know the following rule:
(a b)%m=(a%m) (b%m) The
algorithm idea is to reduce power, for example: 3^ 4 = 3^2 * 3^2

def binaryPow(a,b,m):
    ans=1#当a的幂b为奇数时为了将b变为偶数而存在
    while b>0:#只要b存在
        if b&1==1:#位运算等同于为奇数时
            ans=ans*a%m#将奇数变偶数去掉的a给乘上同时也要%m因为最后b肯定为1所以结果也从这里得到
        a=a*a%m#为偶数时a的平方
        b>>=1#因为上一步所以要将b除2(等同b除2)
    return ans
a,b,m=(int(i) for i in input().split(' '))
print(binaryPow(a,b,m))

The link to the tutorial is recommended to be prepared, you may not be able to watch this video: video

Guess you like

Origin blog.csdn.net/jiahuiandxuehui/article/details/113139599