快速幂取模
快速幂取模算法用来解决a^b%c的问题。
当然,该问题可以使用a*b%c=((a%c)*b)%c的公式,进行化简。但是这样子对于只能解决数值比较小的情况,其算法复杂度依旧是O(n)。为了降低时间复杂度,我们可以使用快速幂取模算法,其时间复杂度可以达到O(log n)。
快速幂取模的本质思想就是:把指数b按二进制展开,从高位到低位依次进行取模运算。其中可以使用递归算法实现,也可以不用递归算法。
由于各项之间都是2倍的关系,所以我们可以使用递归的思想来实现:
递归方式:
int modexp_recursion(long int a, long int b, long int n)
{
int t = 1;
if (b == 0)
return 1;
if (b == 1)
return a%n;
t = modexp_recursion(a, b>>1, n);
t = t*t % n;
if (b&0x1)
{
t = t*a % n;
}
return t;
}
非递归方式:(截取自师兄的代码,那个函数写的漂亮~)
#include<iostream>
using namespace std;
__int64 mod(__int64 a,__int64 b,__int64 c)
{
__int64 m=1;
while(b>=1)
{
if(b%2==1)
m=a*m%c;
a=a*a%c;
b=b/2;
}
return m;
}
int main()
{
__int64 a,b,c,result;
while(scanf("%I64d%I64d%I64d",&a,&b,&c)!=EOF)
{
if(b==0) printf("%I64d\n",1%c);
else
{
result=mod(a,b,c);
printf("%I64d\n",result);
}
}
return 0;
}