-
Notifications
You must be signed in to change notification settings - Fork 10
/
super-pow.py
40 lines (37 loc) · 835 Bytes
/
super-pow.py
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
# Time: O(n), n is the size of b.
# Space: O(1)
# Your task is to calculate a^b mod 1337 where a is a positive integer
# and b is an extremely large positive integer given in the form of an array.
#
# Example1:
#
# a = 2
# b = [3]
#
# Result: 8
# Example2:
#
# a = 2
# b = [1,0]
#
# Result: 1024
class Solution(object):
def superPow(self, a, b):
"""
:type a: int
:type b: List[int]
:rtype: int
"""
def myPow(a, n, b):
result = 1
x = a % b
while n:
if n & 1:
result = result * x % b
n >>= 1
x = x * x % b
return result % b
result = 1
for digit in b:
result = myPow(result, 10, 1337) * myPow(a, digit, 1337) % 1337
return result