Python classical algorithm - Fast power

Fast power

Problem Description:
calculating a ** n% b where a, b and n are both 32-bit non-negative integer
that is a power of n to find the remainder b
exemplary problems:
For example: 31% 2 ** 3 = 2
- -
the code to achieve the following

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

Achieve results

Guess you like

Origin www.cnblogs.com/realwuxiong/p/11987338.html