How to explain this algorithm for calculating the power of a number?

后端 未结 6 1763
生来不讨喜
生来不讨喜 2020-12-15 01:12

I am currently reading Skiena\'s \"The Algorithm Design Manual\".

He describes an algorithm for calculating the power of a number i.e. calculate a^n.

6条回答
  •  忘掉有多难
    2020-12-15 02:08

    This formula a^n = ((a^n/2)^2), which you understand dictates recursive algorithm.

    To get a^n you need first to calculate a^(n/2),
    To get a^(n/2), you need to calculate a^((n/2)/2),
    ... and so on, until (n/2/2/...2) reaches 0, which is the termination condition of the recursion.

    So, the recursive algorithm follows that formula exactly :

    to get power(a,n) you first recursively calculate power(a,n/2) and then return the result adjusting for n being odd/even number.

    There is also wikipedia article about this implementation.

提交回复
热议问题