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

后端 未结 6 1759
生来不讨喜
生来不讨喜 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 01:57

    x = power(a, n/2)
    

    will give you a^n/2. If even this whole statement is squared giving (a^n/2)^2. Now if n is odd, during n/2 a power of a^1 is lost so to get it back it is multiplied with a. This is according to the equation given.

提交回复
热议问题