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
Credits:
Special thanks to @Stomach_ache for adding this problem and creating all test cases.
快速幂取模

求a^b % c ,得到以下函数 ,复杂度为O(logb)
public int PowerMod(int a, int b, int c)
{
int ans = 1;
a = a % c;
while (b > 0)
{
if (b % 2 == 1)
ans = (ans * a) % c;
b = b / 2;
a = (a * a) % c;
}
return ans;
}
这里的b表示为数组的形式,每次b/2比较麻烦,主要慢在这里,复杂度 O(length_of(b)*log b)
public int superPow(int a, int[] b)
{
return PowerMod1(a, b, 1337);
}
public int PowerMod1(int a, int[] b, int c)
{
int ans = 1;
a = a % c;
int bheightestbit=0;
int len=b.length;
while (b[bheightestbit] > 0)
{
if (b[len-1] % 2 == 1)
ans = (ans * a) % c;
boolean setheightest=false;
for(int i=bheightestbit;i<len;i++)
{
int bitnum=b[i];
int mod=bitnum%2;
b[i]=bitnum/2;
if(mod==1&&i<len-1)
b[i+1]+=10;
if(!setheightest&&b[i]>0)
{
setheightest=true;
bheightestbit=i;
}
}
a = (a * a) % c;
}
return ans;
}
本文介绍了一种计算a^b mod c的快速幂取模算法,特别针对a为正整数,b为极大正整数并以数组形式给出的情况。通过实例展示了如何高效地解决此类问题,并提供了一个具体实现该算法的示例代码。

被折叠的 条评论
为什么被折叠?



