Any way faster than pow() to compute an integer power of 10 in C++?

后端 未结 12 908
逝去的感伤
逝去的感伤 2020-12-05 13:25

I know power of 2 can be implemented using << operator. What about power of 10? Like 10^5? Is there any way faster than pow(10,5) in C++? It is a pretty straight-forw

12条回答
  •  感动是毒
    2020-12-05 14:01

    There are certainly ways to compute integral powers of 10 faster than using std::pow()! The first realization is that pow(x, n) can be implemented in O(log n) time. The next realization is that pow(x, 10) is the same as (x << 3) * (x << 1). Of course, the compiler knows the latter, i.e., when you are multiplying an integer by the integer constant 10, the compiler will do whatever is fastest to multiply by 10. Based on these two rules it is easy to create fast computations, even if x is a big integer type.

    In case you are interested in games like this:

    1. A generic O(log n) version of power is discussed in Elements of Programming.
    2. Lots of interesting "tricks" with integers are discussed in Hacker's Delight.

提交回复
热议问题