140. 快速幂

140. 快速幂

中文English

计算an % b,其中a,b和n都是32位的非负整数。

样例

例如 231 % 3 = 2

例如 1001000 % 1000 = 0

挑战

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):
        if n==0:
            return 1%b
        #首先找出规律
        res = []
        s = 0
        for i in range(1,n+1):
            s = a**i
            if i !=  1 and s%b == res[0]:
                break
            res.append(s%b)
        
        p = res[n%len(res)-1]
        return p%b

注:lintcode未通过,代码超出时间限制,你的代码运行时间超过了限制,检查你的时间复杂度。TLE通常是由死循环造成的,思考一下你的时间复杂度是否是最优的。

原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12831219.html