[Lintcode]140. Fast Power

140. Fast Power

  • 本题难度: Medium
  • Topic: Bit Manipulation

Description

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的情况
即:

  1. 二分法,例如3^5 = 13^4 +03^2 + 1*3^1
  2. 每平方一次,都可以转化为之前的余数的平方的余数(这么说有点绕,就是把每个数都可以分成x = bm+n的形式,而对x^2来说,bm(bm+n) 可以整除,不需要考虑,所以只需要 考虑(n^2)%b作为新的n
  • 时间复杂度 O(log(n))

猜你喜欢

转载自www.cnblogs.com/siriusli/p/10359541.html