【题目】
实现函数double power(double base, int exponent),求base的exponent次方。不得使用库函数,同一时候不须要考虑大数问题。
【分析】
此问题非常easy。可是须要重视下面几种情况:
1. exponent < 0 ,结果为整数次方的倒数。
2. exponent = 0, 结果为1;
3. base = 0 && exponent = 0 。 结果为0。本身基底是0 ,0的0次方没有意义。
4. base = 0 && exponent < 0 , 结果为0。
【測试代码】
#include<stdio.h>
#define false 0;
#define true 1;
int g_Invalid_Input ;
int equal(double num1, double num2)
{
if( (num1-num2>-0.0000001) && (num1-num2<0.0000001) )
return true;
return false;
}
double powerwith_unsigned_exponent(double base, unsigned int exponent)
{
double result = 1.0;
for(int i =1 ; i<= exponent; ++i)
result*=base;
return result;
}
double power(double base, int exponent)
{
g_Invalid_Input = false;
if(equal(base, 0.0) && exponent <=0)
{
g_Invalid_Input = true;
return 0.0;
}
unsigned int absExponent = (unsigned int )(exponent);
if(exponent < 0)
absExponent = (unsigned int)(-exponent);
double result = powerwith_unsigned_exponent(base, absExponent);
if(exponent < 0)
result = 1.0 / result;
return result;
}
void main()
{
double result1= power(0,0);
double result2 = power( 0 ,-1);
double result3 = power(2,3);
double result4 = power(2,-3);
double result5 = power(-2,3);
printf("power(0,0) =%f
",result1);
printf("power(0,-1) = %f
",result2);
printf("power(2,3) = %f
",result3);
printf("power(2,-3) = %f
",result4);
printf("power(-2,3) = %f
",result5);
}
【输出】
【改善】
为了更高效,当指数为偶数时。是能够求出一半的结果,再乘以本身,为奇数时,将偶数结果再乘以一次基底,这样递归算的话效率能达到O(lgn)
double powerwith_unsigned_exponent(double base, unsigned int exponent)
{
if(exponent == 0)
return 1;
if(exponent == 1)
return base;
double result = powerwith_unsigned_exponent(base, exponent>>1);
result *= result;
if(exponent & 0x1 ==1)
result *= base;
return result;
}