Efficient way to compute p^q (exponentiation), where q is an integer

前端 未结 3 1514
时光取名叫无心
时光取名叫无心 2020-12-15 20:33

What is an efficient way to compute pq, where q is an integer?

3条回答
  •  情歌与酒
    2020-12-15 20:52

    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.

提交回复
热议问题