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

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

    The function power(...) appears to be written the way it is to handle the effects of integer division. Recall that under integer division rules, the fractional part is discarded. This will only affect odd integers since an even integer divided by two produces no remainder.

    Thus whenever n is an even integer, the value computed for n/2 is exactly equal to n/2 and the top branch of the if can be taken: this is exactly what the equations stipulate.

    Whenever n is an odd integer, the value computed for n/2 is actually equal to floor(n/2). In other words, the statement:

    x = power(a,n/2)
    

    Has actually computed the result

    x = power(a,(n-1)/2)
    

    Meaning that you have permanently lost one 1 from your exponent, and simply returning x^2 will be short one power of a. Hence the bottom branch, which adds back in the power of a.

    If you imagine that instead of integer division, the computer was capable of perfectly lossless real number division, then you could rewrite the function as:

    function power( a, n )
    
        if (n = 0) 
            return(1)
    
        x = power(a,n/2)
    
        return x^2
    

    You can easily satisfy yourself that this is a simple recursive implementation of the second equation you provided in the question.

提交回复
热议问题