二分求幂算法

double powerWithUnsignedExponent(double base,unsigned int exponent)
{
	if(exponent==0)
		return 1;
	if(exponent==1)
		return base;
	double result=powerWithUnsignedExponent(base,exponent>>1);//exponent>>1即exponent/2 
	result*=result;
	if(exponent & 0x1==1)//a & 0x1相当于a%2 
		result*=base;
	return result;
}

 非递归:

int power(int a,int b)
{
	int ans=1;
	while(b!=0)
	{
		if(b%2==1)
			ans*=a;
		b/=2;
		a*=a;
	}
	return ans;
}

 

posted @ 2013-11-08 17:58  紫忆  阅读(921)  评论(2编辑  收藏  举报