关于“快速幂取模”问题,求指教。
小弟初学C,遇到次方求模问题,这是我的代码~
#include<stdio.h>
int main()
{
int N,i;
long long a,b,c,num,m;
scanf("%d",&N);
while(N--)
{
scanf("%lld %lld %lld",&a,&b,&c);
for(i=1,m=1;i<=b;i++)
m=m*a;
num=m%c;
printf("%lld\n",num);
}
return 0;
}
但是在网上看有更好的方法可以快速幂取模,可是研究半天没研究懂= =,各位前辈能否指教下,详细的说说。。。下面是我在网上找到的快速幂取模的代码.
long exp_mod(long a,long b,long c)
{
long t;
if(b==0) return 1%c;
if(b==1) return a%c;
t=exp_mod(a,b/2,c);
t=t*t/c;
if((b&1)==1)
t=t*a/c;
return t;
} C
[解决办法]
代码中有些错误:
long exp_mod(long a,long b,long c)
{
long t;
if(b==0) return 1%c;
if(b==1) return a%c;
t=exp_mod(a,b/2,c);
t=t*t%c;
if((b&1)==1)
t=t*a%c;
return t;
}