//快速幂,x^y,此算法递归耗空间
unsigned int fast_pow ( unsigned int x, unsigned int y ){
unsigned int temp;
if ( y == 1 )
return x;
else if ( (unsigned int)y % 2 == 0 ) {
temp = fast_pow(x,y/2); // 用临时变量减少重复的运算
return temp*temp;
}
else {
temp = fast_pow(x,(y-1)/2);
return temp*temp*x;
}
}
//快速幂,x^n 利用位运算
int pow3(int x,int n){
if(n==0) return 1;
else {
while((n&1)==0){
n>>=1;
x*=x;
}
}
int result=x;
n>>=1;
while(n!=0){
x*=x;
if(n&1) result*=x;
n>>=1;
}
return result;
}
//在上面算法的基础上利用(x*y) mod n = x mod n * y mod n公式算(x^y) mod n
lld mod(lld a,lld b,lld m)
{
lld ret=1;
a%=m;
while(b)
{
if(b&1)ret=ret*a%m;
b>>=1;
a=a*a%m;
//printf("b=%I64d\n",b);
}
return ret;
}
三个快速计算幂的函数
最新推荐文章于 2023-10-09 20:43:40 发布