高效率的取幂运算
计算X^N的常见算法是使用N-1次乘法自乘,时间复杂度为O(n)。使用下面的递归算法更好,时间复杂度为O(logn):
template<class T>
T Pow(T x, unsigned int N)
{
	if (0==N)
	{
		return 1;
	}
	else if (1==N)
	{
		return x;
	}
	else if (0==N%2)
	{
		return Pow(x*x, N/2);
	}
	else
	{
		return Pow(x*x, N/2)*x;
	}
} 
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号