Your task is to calculate ab 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
Solution
(Super-Pow.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
public int superPow ( int a , int [] b ) {
int ret = 1 ;
for ( int i = b . length - 1 ; i >= 0 ; i --){
ret = ret * pow ( a , b [ i ], 1337 )% 1337 ;
a = pow ( a , 10 , 1337 );
}
return ret ;
}
// 计算a^b%c
public int pow ( int a , int b , int c ){
long ret = 1 ;
long p = a ;
while ( b > 0 ){
if (( b & 1 )== 1 )
ret = ( ret * p )% c ;
p = ( p * p )% c ;
b = b >> 1 ;
}
return ( int )( ret % c );
}
}
c mod m = (a ⋅ b) mod m = [(a mod m) ⋅ (b mod m)] mod m
(Super-Pow.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution ( object ):
def superPow ( self , a , b ):
"""
:type a: int
:type b: List[int]
:rtype: int
"""
ans = 1
mod = 1337
for bi in b [:: - 1 ]:
ans = ans * a ** bi % mod
a = a ** 10 % mod
return ans