这个是快速的版本:
-
package main
-
-
import "fmt"
-
-
func fib(n uint) (ret int64){
-
-
var index uint = 0
-
-
var i int64 = 1
-
var j int64 = 0
-
-
for index < n {
-
index += 1
-
i,j = i+j,i
-
}
-
-
return j
-
}
-
-
func main(){
-
-
fmt.Printf("%d\n",fib(40))
- }
-
package main
-
import "fmt"
-
-
func fib(n uint) uint64{
-
-
if n == 0{
-
return 0
-
}else if n == 1 {
-
return 1
-
}else {
-
return fib(n-1)+fib(n-2)
-
}
-
}
-
-
-
func main(){
-
fmt.Printf("%d\n",fib(40))
- }
实验证明,当计算fibnacci(60)的时候,fib_slow慢到不能忍受,fib的效率依然是O(n)。
-
manu@manu-hacks:~/code/go/self$ time ./fib
-
102334155
-
-
real 0m0.008s
-
user 0m0.004s
-
sys 0m0.000s
-
manu@manu-hacks:~/code/go/self$ time ./fib_slow
-
102334155
-
-
real 0m2.643s
-
user 0m2.604s
-
sys 0m0.004s
- manu@manu-hacks:~/code/go/self$
参考文献:
1 An introduction to programming in GO