Calculate the a^n % b where a, b and n are all 32bit positive integers.
Example
For 231 % 3 = 2
For 1001000 % 1000 = 0
Challenge
O(logn)
class Solution:
"""
@param a: A 32bit integer
@param b: A 32bit integer
@param n: A 32bit integer
@return: An integer
"""
def fastPower(self, a, b, n):
# write your code here
if n == 0:
return 1%b
res = 1
containt = a%b
while(n>=1):
if n%2 == 1:
res = (res*containt)%b
containt = (containt*containt)%b
n = n//2
return res
参考了一下https://www.jiuzhang.com/solution/fast-power/#tag-highlight-lang-python的思路。
可以转化为k*b + x的情况
即:
原文:https://www.cnblogs.com/siriusli/p/10359541.html