我知道2的幂可以用<<算子实现。那10倍的功率呢?比如10^5?在C++中有比pow(10,5)更快的方法吗?这是一个相当直截了当的手工计算.但对计算机来说似乎不容易因为数字的二进制表示..。假设我只对整数幂,10^n感兴趣,其中n是整数。
发布于 2022-09-06 11:40:59
基于constexpr函数的泛型表生成器。浮点部分需要c++20和gcc,但非浮点部分适用于c++17。如果将"auto“类型改为"long”,则可以使用c++14。测试不正确。
#include <cstdio>
#include <cassert>
#include <cmath>
// Precomputes x^N
// Inspired by https://stackoverflow.com/a/34465458
template<auto x, unsigned char N, typename AccumulatorType>
struct PowTable {
constexpr PowTable() : mTable() {
AccumulatorType p{ 1 };
for (unsigned char i = 0; i < N; ++i) {
p *= x;
mTable[i] = p;
}
}
AccumulatorType operator[](unsigned char n) const {
assert(n < N);
return mTable[n];
}
AccumulatorType mTable[N];
};
long pow10(unsigned char n) {
static constexpr PowTable<10l, 10, long> powTable;
return powTable[n-1];
}
double powe(unsigned char n) {
static constexpr PowTable<2.71828182845904523536, 10, double> powTable;
return powTable[n-1];
}
int main() {
printf("10^3=%ld\n", pow10(3));
printf("e^2=%f", powe(2));
assert(pow10(3) == 1000);
assert(powe(2) - 7.389056 < 0.001);
}
https://stackoverflow.com/questions/18581560
复制相似问题