Integer power
Title: Implement the function double Power (double base, int exponent),
find base to the exponent power. Do not use library functions, and do not need to consider large numbers
Because there is no need to consider large numbers, it seems to be very simple, just add up.
double Power(double base,int exponent)
{
double result=1.0;
for(int i=0;i<=exponent;++i)
result*=result;
return result;
}
But there is a serious problem. What should I do if the input exponent is less than 1 (0 and negative)? Obviously the above code does not consider
After consideration, the code is as follows:
bool g_InvalidInput=false;
double Power(double base,int exponent)
{
g_InvalidInput=false;
if(equal(base,0.0) && exponent<0)
{
g_InvalidInput=true;
return 0.0;
}
unsigned int absExponent=(unsigned int)(exponent);
if(exponent<0)
absExponent=(unsigned int)(-exponent);
double result=PowerWithUnsignedExponent(base,absExponent)
if(exponent<0)
result=1.0/result;
return result;
}
double PowerWithUnsignedExponent(double base,unsigned int exponent)
{
double result=1.0;
for(int i=1;i<=exponent;++i)
result*=base;
return result;
}
Although there is a correct answer, you will find that such efficiency is too low. Is there any simple way?
Of course there is!
Imagine this: if our goal is to find a number to the 32nd power, if we know its 16th power, then we can just square it once more on the basis of the 16th power. 16 can be squared to the 8th power...
In other words, we can use the following formula to find the n-th power of a:
This formula is easily implemented by recursion. The new PowerWithUnsignedExponent code is as follows:
PowerWithUnsignedExponent(double base,unsigned int exponent)
{
if(exponent==0)
return 1;
if(exponent==1)
return base;
double result=PowerWithUnsignedExponent(base,expnent>>1);
result*=result;
if(exponent & 0x1==1)
return*=base;
return result;
}
So you can get efficient code
The complete code is as follows:
double Power(double base, int exponent)
{
g_InvalidInput = false;
if (equal(base, 0.0) && exponent < 0)
{
g_InvalidInput = true;
return 0.0;
}
unsigned int absExponent = (unsigned int) (exponent);
if (exponent < 0)
absExponent = (unsigned int) (-exponent);
double result = PowerWithUnsignedExponent(base, absExponent);
if (exponent < 0)
result = 1.0 / result;
return result;
}
double PowerWithUnsignedExponent(double base, unsigned int exponent)
{
if (exponent == 0)
return 1;
if (exponent == 1)
return base;
double result = PowerWithUnsignedExponent(base, exponent >> 1);
result *= result;
if ((exponent & 0x1) == 1)
result *= base;
return result;
}
bool equal(double num1, double num2)
{
if ((num1 - num2 > -0.0000001) && (num1 - num2 < 0.0000001))
return true;
else
return false;
}
——————————————————————————————————————————
Reference book "Sword Finger Offer 》