What is an efficient way to compute pq, where q is an integer?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- ceil conterpart for Math.floorDiv in Java?
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
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).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.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.