考慮到n個x相乘式子的對稱關係,能夠對上述方法進行改進,從而獲得一種時間複雜度爲O(logn)的方法,遞歸關係能夠表示爲pow(x,n) = pow(x,n/2)*pow(x,n-n/2)ide
func pow(x float64, n int) float64 { if n == 0 { return 1.0 } if n < 0 { return 1.0 / pow(x, -n) } half := pow(x, n>>1) //example: n = 3 3/2 = 1 if n%2 == 0 { return half * half } else { return half * half * x } }
除了上述方法,這裏還提到了一種十分巧妙而且快速的方法,原文描述以下:oop
Consider the binary representation of n. For example, if it is "10001011", then x^n = x^(1+2+8+128) = x^1 * x^2 * x^8 * x^128. Thus, we don't want to loop n times to calculate x^n. To speed up, we loop through each bit, if the i-th bit is 1, then we add x^(1 << i) to the result. Since (1 << i) is a power of 2, x^(1<<(i+1)) = square(x^(1<<i)). The loop executes for a maximum of log(n) times.spa
func my_pow(x float64, n int) float64 { if n == 0 { return 1.0 } if n < 0 { return 1.0 / my_pow(x, -n) } var result float64 = 1.0 for ; n > 0; n = n >> 1 { if n&1 != 0 { result *= x } x = x * x } return result }
完整代碼 :code
package main import ( "fmt" ) func pow(x float64, n int) float64 { if n == 0 { return 1.0 } if n < 0 { return 1.0 / pow(x, -n) } half := pow(x, n>>1) //example: n = 3 3/2 = 1 if n%2 == 0 { return half * half } else { return half * half * x } } func my_pow(x float64, n int) float64 { if n == 0 { return 1.0 } if n < 0 { return 1.0 / my_pow(x, -n) } var result float64 = 1.0 for ; n > 0; n = n >> 1 { if n&1 != 0 { result *= x } x = x * x } return result } func main() { fmt.Printf("pow result %v \n", my_pow(6.0, 2)) }