函数平方pow(x,n)的求法
2016-01-28 15:19
429 查看
考虑到n个x相乘式子的对称关系,可以对上述方法进行改进,从而得到一种时间复杂度为O(logn)的方法,递归关系可以表示为pow(x,n) = pow(x,n/2)*pow(x,n-n/2)
除了上述方法,这里还提到了一种十分巧妙并且快速的方法,原文描述如下:
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.
完整代码 :
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 } }
除了上述方法,这里还提到了一种十分巧妙并且快速的方法,原文描述如下:
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.
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
}
完整代码 :
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)) }
相关文章推荐
- google map geocoder 地理位置编码的实例
- css 属性通配符选择器
- Ubuntu10.04下的使用使用华为E1750 3G模块
- URLs对象 blob URL
- filereader api 类型
- ASP.net 验证码(C#) MVC
- OC基础--self关键字&super关键字
- 广告点击率 CTR预估中GBDT与LR融合方案
- select转移工具箱
- 并查集
- 创建或删除文件夹
- Android之网络编程(四)解析 JSON 格式数据
- 用DrawText实现高效的Android倒计时功能。
- 数据结构基础(8) --单链表的设计与实现(1)之基本操作
- SQL字符串函数
- Lua 在C程序中进行Lua表操作
- 说说分布式事务
- SVG
- 静态化 - 伪静态技术(PHP正则表达式实现)
- UVA 12333