golang版斐波那契数列

我们终此一生,就是要摆脱他人的期待,找到真正的的自己

简单版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main

import (
"fmt"
"time"
)

func main() {

go loading(time.Millisecond * 100)
fmt.Println("\n", fib(45))

}

func fib(x int) int {
if x < 2 {
return x
}

return fib(x-2) + fib(x-1)
}

func loading(delay time.Duration) {
for {
for _,r := range `-\|/` {
fmt.Printf("\r%c", r)
time.Sleep(delay)
}
}
}

并发版

使用无缓冲通道实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
"fmt"
)

func fibonacci(n int, c chan int) {

x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}

close(c)
}

func main() {
c := make(chan int, 60)

go fibonacci(cap(c), c)

for i := range c {
fmt.Println(i)
}
}