在C++中将整数提高到正整数幂的正确方法是什么

What is the correct way to raise an integer to a positive integer power in C++?

本文关键字:整数 是什么 方法 C++      更新时间:2023-10-16

我们知道,由于各种原因,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) .如果两个ab和结果都适合一个 32 位整数,就不会有不准确!

原因是 64 位双精度完全覆盖了 32 位整数的范围。

虽然 Kerrek 的答案是正确的,但 g++ 中还有一个"秘密"功能可以有效地做到这一点。 如果您查看SGI电源功能,它可以很容易地适应您想要的功能:

http://www.sgi.com/tech/stl/power.html

在 g++ 中,这是作为 __gnu_cxx::p ower 实现的。 不过,您可能不应该在生产代码中使用这些东西......

除了这里的其他答案,维基百科上还有一篇很好的文章在这里解释了各种不同的实现 ->链接