140. Fast Power

題目

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章