Power(int base, int exponent) 函数实现

这个是个高效的算法,时间复杂度为 O(logn)

原理:

a的n次方:

Power(int base, int exponent) 函数实现

#include<iostream>
#include<cmath>
using namespace std; double PowerWithUnisgnedExponent(double base ,unsigned int exponent)
{
if(exponent == 0)
return 1;
if(exponent == 1)
return base; double result = PowerWithUnisgnedExponent(base, exponent >> 1);
result *= result;
if(exponent & 0x1 == 1)
result *=base;
return result;
} double power(double base, int exponent)
{
double result = PowerWithUnisgnedExponent(base,abs(exponent));
if(exponent < 0)
return 1.0/result;
else
return result;
} int main()
{
int base = 2;
int exponent = 10;
cout << power(base,exponent); return 0;
}
上一篇:【转载】聊一聊C#的Equals()和GetHashCode()方法


下一篇:mysql(一)--mysql架构和执行流程