題目
https://www.lintcode.com/problem/fast-power/description?_from=ladder&&fromId=2
實現
拆分:
a ^ n % b = (a ^ n/2 % b) * (a ^ n/2 % b)
還要考慮如果 n 是奇數的情況下,還要再 %b 一次
代碼
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):
if n == 0:
return 1 % b
if n == 1:
return a % b
result = self.fastPower(a, b, n // 2)
result = (result * result) % b
if n % 2 == 1:
result = (result * a) % b
return result