卖萌的弱渣

I am stupid, I am hungry.

Fast Power

Fast Power

Calculate the an % b where a, b and n are all 32 bit integers.

Example

For 231 % 3 = 2

For 1001000 % 1000 = 0

Challenge

O(logn)

Solution

  • Time: O(logn)

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

  • a2 %b = ((a%b) * (a%b))%b
  • a3 %b = ((a2%b) * (a%b))%b
(Fast-Power.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Recursive
class Solution:
    """
    @param a, b, n: 32bit integers
    @return: An integer
    """
    def fastPower(self, a, b, n):
        # write your code here
        if n==0:
            return 1%b
        if n==1:
            return a%b
        result = self.fastPower(a,b,n/2)
        result = (result * result)%b
        # 若n是奇数,需要多乘一次
        if n%2 == 1:
            result = (result*a)%b
        return result

# Array
class Solution:
    """
    @param a, b, n: 32bit integers
    @return: An integer
    """
    def fastPower(self, a, b, n):
        # write your code here
        # (a * b) % p = ((a % p ) * (b % p)) % p
        if n==0:
            return 1%b
        array = [1] * (n+1)
        array[0] = 1%b
        array[1] = a%b
        for i in range(2,n+1):
            j = i
            while j>0:
                if j==1:
                    array[i] *= array[1]
                    break
                else:
                    array[i] *= array[j/2];
                    j -= j/2
            array[i] %= b
        return array[n]