一般的乘方算法,时间复杂度是O(n)
非递归方式
int Power(int num, int exponent)
{
int result = 1;
while (exponent) {
if (exponent & 1) {
result *= num;
}
num *= num;
exponent = exponent >> 1;
}
return result;
}
通过下面的方式,能达到O(logn)
递归方式
递归的普通操作方式
long power(long num, long exponent)
{
if (exponent == 0)
return 1;
if (exponent == 1)
return num;
if (exponent % 2 == 1)
return num*power(num*num, exponent / 2);
else
return power(num*num, exponent / 2);
递归的位操作方式
int Power(int num, int exponent)
{
if (1 == exponent) {
return num;
}
if (0 == exponent) {
return 1;
}
int result = 0;
if (exponent & 1) {//if exponent is odd
result = num * Power(num * num, exponent >> 1);
} else {//if exponent is even
result = Power(num * num, exponent >> 1);
}
return result;
}
完整的程序代码:
#include <iostream>
using namespace std;
long power(long num, long exponent)
{
if (exponent == 0)
return 1;
if (exponent == 1)
return num;
if (exponent % 2 == 1)
return num*power(num*num, exponent / 2);
else
return power(num*num, exponent / 2);
//或者采用下边位操作方式
//if (exponent & 1) //if exponent is odd
//{
// result = num * Power(num * num, exponent >> 1);
//}
//else //if exponent is even
//{
// result = Power(num * num, exponent >> 1);
//}
}
int main()
{
long x, n;
cout << "请输入x和n的值:";
cin >> x >> n;
cout << "power(x,n)的值:" << power(x, n) << endl;
system("pause");
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。