在C++中将整数提高到正整数幂的正确方法是什么
What is the correct way to raise an integer to a positive integer power in C++?
我们知道,由于各种原因,C++没有标准的整数幂函数。我正在用相当小的整数执行精确的算术,计算幂的正确方法是什么?
标准的快速幂法使用重复平方法:
uint_t power(uint_t base, uint_t exponent)
{
uint_t result = 1;
for (uint_t term = base; exponent != 0; term = term * term)
{
if (exponent % 2 != 0) { result *= term; }
exponent /= 2;
}
return result;
}
步数在 exponent
的值中是对数的。该算法可以简单地扩展到模幂。
更新:这是该算法的修改版本,它执行的乘法更少,并且可以更有效地处理一些琐碎的情况。此外,如果您知道指数永远不会为零,并且基数永远不会为零或一,您甚至可以删除初始检查:
uint_t power_modified(uint_t base, uint_t exponent)
{
if (exponent == 0) { return 1; }
if (base < 2) { return base; }
uint_t result = 1;
for (uint_t term = base; ; term = term * term)
{
if (exponent % 2 != 0) { result *= term; }
exponent /= 2;
if (exponent == 0) { break; }
}
return result;
}
您可以使用std::pow(double a, double b)
.如果两个a
、b
和结果都适合一个 32 位整数,就不会有不准确!
原因是 64 位双精度完全覆盖了 32 位整数的范围。
虽然 Kerrek 的答案是正确的,但 g++ 中还有一个"秘密"功能可以有效地做到这一点。 如果您查看SGI电源功能,它可以很容易地适应您想要的功能:
http://www.sgi.com/tech/stl/power.html
在 g++ 中,这是作为 __gnu_cxx::p ower 实现的。 不过,您可能不应该在生产代码中使用这些东西......
除了这里的其他答案,维基百科上还有一篇很好的文章在这里解释了各种不同的实现 ->链接
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将一系列整数放入类的最佳方法是什么?
- 比较C++中两个整数的最有效和最干净的方法是什么?
- 为什么此指针值不能转换为整数的规则是什么?
- 为对象分配整数.输出将是什么?
- 初始化不是整数的巨大常量多维数组的最佳方法是什么?
- 在C++中,将无符号整数转换为八进制表示,反之亦然的最佳方法是什么
- " ans += (a[i] - ans * r > 0); "是什么意思,其中 ans,r 是整数,a[i] 是数组元素?
- C++ 大整数,这是什么意思
- 当我使用我的向量名称后跟包含整数变量的括号时,括号是什么意思
- “*(无符号整数*)((无符号整数)块 + n*i)”是什么意思
- 在某些范围更新后获取整数数组的最终状态的有效算法是什么?
- 实现整数除法向上舍入的正确方法是什么?
- 可用于存储和管理整数集合的最佳C++数据结构是什么
- 在 c++ 中用 '1' 替换整数'0'的最佳方法是什么
- c中未签名整数的类型是什么
- 对应于 AS3 编号(整数)的C++数据类型是什么?
- 在C++中将整数提高到正整数幂的正确方法是什么
- 这是什么C++语言结构:#(即哈希)整数"path_to_header_or_cpp_file"<integer>?
- 当我们在 c++ 中将常量整数引用分配给整数指针时,行为是什么