Fast Power

题目描述

  • power(x, n)
  • power(x, n) % d

解题方法

(a * b) % p = (a % p * b % p) % p

Solution

递归

class Solution(object):
    def myPow(self, x, n):
        """
        :type x: float
        :type n: int
        :rtype: float
        """
        if x == 0:
            return 0
        if n == 0:
            return 1

        if n < 0:
            return 1/self.myPow(x, -n)

        result = self.myPow(x, n/2)
        result *= result
        if n % 2 != 0:
            result *= x

        return result
class Solution:
    # @param x : integer
    # @param n : integer
    # @param d : integer
    # @return an integer
    def pow(self, x, n, d):
        if x == 0:
            return 0 % d
        if n == 0:
            return 1 % d
        if n == 1:
            return x % d

        result = self.pow(x, n/2, d)
        result *= result
        result %= d # 先计算过sqaure再 module d
        if n % 2 == 1:
            result = result * x % d

        return result

iterative

Reference