Pythonの古典アルゴリズム - 高速パワー

高速電力

問題の説明:
** N、B及びnは両方とも32ビットの負でない整数であり、%Bを算出
bの残りを見つけるためのn乗である
:典型的な問題
例:31%2 ** 3 = 2
- -
以下のことを実現するためのコード

class Solution:
    def fastPower(self, a, b, n):
        ans = 1
        while n > 0:
            if n % 2 == 1:
                ans = ans * a % b
            a = a * a % b
            n = n / 2
        return ans % b


if __name__ == '__main__':
    solution = Solution()
    print(solution.fastPower(2, 31, 3))

結果を実現

おすすめ

転載: www.cnblogs.com/realwuxiong/p/11987338.html