计算 p^q(求幂)的有效方法,其中 q 是整数
计算 pq(其中 q 是整数)的有效方法是什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
计算 pq(其中 q 是整数)的有效方法是什么?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
平方求幂仅使用 O(lg q) 乘法。
这应该适用于任何 monoid (
T
,operator*< /code>),其中由
1
构造的T
是单位元素。这包括所有数字类型。将其扩展到
signed q
很简单:只需将 1 除以上述结果即可得到q
的绝对值(但像往常一样,计算绝对值时要小心) 。Exponentiation by squaring uses only O(lg q) multiplications.
This should work on any monoid (
T
,operator*
) where aT
constructed from1
is the identity element. That includes all numeric types.Extending this to
signed q
is easy: just divide one by the result of the above for the absolute value ofq
(but as usual, be careful when computing the absolute value).假设
^
表示求幂,并且q
是运行时变量,请使用std::pow(double, int)
。编辑:为了完整起见,由于对此答案的评论:我问了问题 为什么 std::pow(double, int) 从 C++ 中删除11?关于缺失的函数,事实上
pow(double, int)
在C++0x中并没有被删除,只是语言被改变了。然而,由于结果准确性问题,图书馆可能实际上并没有对其进行优化。即使我仍然会使用
pow
,直到测量表明它需要优化。Assuming that
^
means exponentiation and thatq
is runtime variable, usestd::pow(double, int)
.EDIT: For completeness due to the comments on this answer: I asked the question Why was std::pow(double, int) removed from C++11? about the missing function and in fact
pow(double, int)
wasn't removed in C++0x, just the language was changed. However, it appears that libraries may not actually optimize it due to result accuracy concerns.Even given that I would still use
pow
until measurement showed me that it needed to be optimized.我假设 ^ 你指的是幂函数,而不是按位异或。
任何类型的 p 和任何正积分 q 的有效幂函数的开发是 Stepanov 和 McJones 的《编程元素》一书中的整个章节 3.2。书中的语言不是C++,但很容易翻译成C++。
它涵盖了多种优化,包括通过平方求幂、转换为尾递归然后迭代以及累积变量消除,并将优化与类型正则性和关联运算的概念联系起来,以证明它适用于所有此类类型。
I assume by ^ you mean power function, and not bitwise xor.
The development of an efficient power function for any type of p and any positive integral q is the subject of an entire section, 3.2, in Stepanov's and McJones's book Elements of Programming. The language in the book is not C++, but is very easily translated into C++.
It covers several optimizations, including exponentiation by squaring, conversion to tail recursion then iteration, and accumulation-variable elimination, and relates the optimizations to the notions of type regularity and associative operations to prove it works for all such types.