# 整数的非负整数次幂（不考虑大数）

## 线性求幂

typedef long long LL;
LL pow(int base, int exponent) {
LL ans = 1;
for (int i = 0; i < exponent; ++i) {
ans *= base;
}
return ans;
}

## 快速幂算法登场

a11=a10112=a10002+102+12=a10002a102a12=a8a2a1

typedef long long LL;
LL pow(int base, int exponent) {
LL ans = 1, last_pow = base;
while (exponent > 0) {
// 如果最低位为1
if ((exponent & 1) != 0)
ans = ans * last_pow ;
exponent = exponent >> 1;
last_pow = last_pow * last_pow;
}
return ans;
}

# 整数次幂

ax=1axx

a0=1a0

typedef double NumberType;

// 计算非负整数次幂的函数
NumberType powWithoutNegativeExp(NumberType base, int exponent) {
NumberType ans = 1, last_pow = base;
while (exponent > 0) {
if ((exponent & 1) != 0)
ans = ans * last_pow ;
exponent = exponent >> 1;
last_pow = last_pow * last_pow;
}
return ans;
}

// 浮点数相等的判断比较特别
bool equalD(NumberType numA, NumberType numB) {
static const NumberType ERROR = 1e-12;
return (numA - numB <= ERROR && numA - numB >= -ERROR);
}

// 处理各种情况的幂运算的函数
NumberType pow(NumberType base, int exponent) {
// 0的0次幂没有意义，抛出异常
if (exponent == 0 && equalD(base, 0)) {
throw logic_error("Zero's zero exponent is undefine.");
}

bool isNegative = false;
if (exponent < 0) {
isNegative = true;
exponent = -exponent;
}

NumberType result = powWithoutNegativeExp(base, exponent);
return isNegative ? 1 / result : result;
}

#include <iostream>
#include <stdexcept>
using namespace std;

typedef double NumberType;

NumberType powWithoutNegativeExp(NumberType base, int exponent) {
NumberType ans = 1, last_pow = base;
while (exponent > 0) {
if ((exponent & 1) != 0)
ans = ans * last_pow ;
exponent = exponent >> 1;
last_pow = last_pow * last_pow;
}
return ans;
}

bool equalD(NumberType numA, NumberType numB) {
static const NumberType ERROR = 1e-12;
return (numA - numB <= ERROR && numA - numB >= -ERROR);
}

NumberType pow(NumberType base, int exponent) {
if (exponent == 0 && equalD(base, 0)) {
throw logic_error("Zero's zero exponent is undefine.");
}

bool isNegative = false;
if (exponent < 0) {
isNegative = true;
exponent = -exponent;
}

NumberType result = powWithoutNegativeExp(base, exponent);
return isNegative ? 1 / result : result;
}

int main() {
for (double i = 1.1; i < 1.5; i+=0.1) {
for (int j = 1; j < 10; ++j)
cout << i << ' ' << j << ' ' << pow(i, j) << endl;
}

return 0;
}

#### pow()函数自实现

2016-05-03 15:14:00

#### pow(x,y)函数的用法及实现算法

2015-07-11 18:15:05

#### 探索c++的函数pow()的实现方法·数学与程序设计的结合(zz)

2008-02-29 19:58:00

#### c语言里的pow函数

2018-03-10 20:14:53

#### pow函数使用

2014-11-07 20:27:22

#### math.pow()函数

2015-04-22 10:15:08

#### Math.pow函数的重写

2014-03-24 23:42:51

#### Linux下的C语言pow()函数引出的问题

2016-04-06 09:37:07

#### OpenGL ES着色器语言之内建函数（官方文档第八章）

2012-07-22 00:33:26

#### GLSL 内建函数

2012-08-17 10:50:54