加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

[Lintcode]140. Fast Power

发布时间:2020-12-14 04:25:18 所属栏目:大数据 来源:网络整理
导读: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: """ @para

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))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读