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

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

原理:

a的n次方:


 

#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;
}

 

 

 

posted on 2013-09-30 21:20  you Richer  阅读(521)  评论(0编辑  收藏  举报