一.题目:
计算 (a^b)%1377 的值(其中,a 是一个整数,b 是一个由数组表示的非常大的正整数).
Example 1:
Input: a = 2, b = [3]
Output: 8
Example 2:
Input: a = 2, b = [1,0]
Output: 1024
二.解题思路:
需要用到的数学知识
- a^b % 1337 = (a%1337)^b % 1337
- xy % 1337 = ((x%1337) * (y%1337)) % 1337, 其中xy是两个数x和y的乘积.
代码如下:
def superPow(self, a, b):
"""
:type a: int
:type b: List[int]
:rtype: int
"""
def mul(x, y):
return (x*y)%k
#(a^n)%k
def pow(a, n):
ret = 1
for i in range(n):
ret = mul(ret, a)
return ret
k = 1337
a %= k #1. a^b % 1337 = (a%1337)^b % 1337
ret = 1
for n in b: #2. xy % 1337 = ((x%1337) * (y%1337)) % 1337
ret = mul(pow(ret,10), pow(a,n))
return ret