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

时间:2022-05-03 12:47:19

这个是个高效的算法,时间复杂度为 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;
}