当前位置: 编程技术>c/c++/嵌入式
C语言求幂计算的高效解法
来源: 互联网 发布时间:2014-10-29
本文导语: 本文实例演示了C语言求幂计算的高效解法。很有实用价值。分享给大家供大家参考。具体方法如下: 题目如下: 给定base,求base的幂exp 只考虑基本功能,不做任何边界条件的判定,可以得到如下代码: #include using namespac...
本文实例演示了C语言求幂计算的高效解法。很有实用价值。分享给大家供大家参考。具体方法如下:
题目如下:
给定base,求base的幂exp
只考虑基本功能,不做任何边界条件的判定,可以得到如下代码:
#include
using namespace std;
int cacExp(int base, int exp)
{
int result = 1;
int theBase = 1;
while (exp)
{
if (exp & 0x01)
result = result * base;
base = base * base;
exp = exp >> 1;
}
return result;
}
int getRecurExp(int base, int exp)
{
if (exp == 0)
{
return 1;
}
if (exp == 1)
{
return base;
}
int result = getRecurExp(base, exp >> 1);
result *= result;
if (exp & 0x01)
result *= base;
return result;
}
int main()
{
for (int i = 1; i < 10; i++)
{
int result = cacExp(2, i);
//int result = getRecurExp(2, i);
cout 1);
result *= result;
if (exp & 0x01)
result *= base;
return result;
}
double _myPow2(double base, int exp)
{
if (exp == 0)
return 1;
double result = 1;
while (exp)
{
if (exp & 0x01)
result *= base;
base *= base;
exp = exp >> 1;
}
return result;
}
double myPow(double base, int exp)
{
if (equalZero(base))
return 0;
if (exp == 0)
return 1;
bool flag = false;
if (exp < 0)
{
flag = true;
exp = -exp;
}
double result = _myPow2(base, exp);
if (flag)
{
result = 1 / result;
}
return result;
}
void main()
{
double base = 2.0;
int exp = -5;
double result = myPow(base, exp);
cout