784人阅读 评论(0)

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

## 线性求幂

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

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：130505次
• 积分：2707
• 等级：
• 排名：第13876名
• 原创：142篇
• 转载：21篇
• 译文：1篇
• 评论：27条
最新评论