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

后端 未结 6 1721
生来不讨喜
生来不讨喜 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:12

    First of all, let's fix your algorithm:

    function power( a, n )
        if (n = 0) 
            return(1)
    
        x = power(a,n/2)
    
        if (n is even) 
            return(x*x)
        else 
            return(a*x*x)
    

    Say you want to calculate power(2,8), that is, 2^8 (^ is not XOR here, of course).

    • 1) (a=2, n=8). 2^8 = (2^4)^2, so we have to calculate x=2^4, and then x*x to yield the final result. We have to call power() again to get x. power(2,4).

    • 2) (a=2, n=4). 2^4 = (2^2)^2, so we have to calculate x=2^2, and then x*x to yield the final result. We have to call power() again to get x. power(2,2).

    • 3) (a=2, n=2). 2^2 = (2^1)^2, so we have to calculate x=2^1, and then x*x to yield the final result. We have to call power() again to get x. power(2,1).

    • 4) (a=2, n=1). 2^1 = (2^0)^2, so we have to calculate x=2^0, and then a*x*x to yield the final result. We have to call power() again to get x. power(2,0).

    • 5) (a=2, n=0). 2^0 = 1 because n is 0, so we have the value of x that is returned to step #4.

    • 4) (a=2, n=1, x=1). The final result for this step is a*x*x = 2*1*1=2, which is the value to be assigned to x in step #3.

    • 3) (a=2, n=2, x=2). The final result for this step is x*x = 2*2 = 4. This is the result to be assigned to x in step #2.

    • 2) (a=2, n=4, x=4). The final result for this step is x*x = 4*4 = 16. This is the result to be assigned to x in step #1.

    • 1) (a=2, n=8, x=16). The final result for this step is x*x = 16*16 = 256. This is the result to be returned by power(2,8).

提交回复
热议问题