# go语言实现斐波数列

chenxun2009 · · 1281 次点击 · · 开始浏览

### 递归实现

```package main

import "fmt"

func fibonacci(num int) int{
if num<2{
return 1
}

return fibonacci(num-1) + fibonacci(num-2)
}

func main(){
for i := 0; i<10; i++{
nums := fibonacci(i)
fmt.Println(nums)
}
}```

### 闭包实现

```package main

import "fmt"

func fibonacci() func() int{
a, b := 0, 1
return func() int{
a, b = b, a+b
return a
}
}

func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
```

```package main

import(
"fmt"
)

func fib(n int, c chan int){
a,b :=0,1
for i:=0; i<n; i++{
a,b = b,a+b
c <- a
}

close(c)
}

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

fib(cap(c),c)

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

}```

```package main
import "fmt"

var fibs [40]uint64

func fib_function(n int) (res uint64) {
if fibs[n] !=0{
res = fibs[n]
return
}

if(n<=1){
res = 1
}else{
res = fib_function(n-1)+fib_function(n-2)
}

fibs[n] = res
return
}

func main(){
fib_function(10)

for i := 0; i<10;i++{
fmt.Println(fibs[i])
}
}
```

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

### 递归实现

```package main

import "fmt"

func fibonacci(num int) int{
if num<2{
return 1
}

return fibonacci(num-1) + fibonacci(num-2)
}

func main(){
for i := 0; i<10; i++{
nums := fibonacci(i)
fmt.Println(nums)
}
}```

### 闭包实现

```package main

import "fmt"

func fibonacci() func() int{
a, b := 0, 1
return func() int{
a, b = b, a+b
return a
}
}

func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
```

```package main

import(
"fmt"
)

func fib(n int, c chan int){
a,b :=0,1
for i:=0; i<n; i++{
a,b = b,a+b
c <- a
}

close(c)
}

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

fib(cap(c),c)

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

}```

```package main
import "fmt"

var fibs [40]uint64

func fib_function(n int) (res uint64) {
if fibs[n] !=0{
res = fibs[n]
return
}

if(n<=1){
res = 1
}else{
res = fib_function(n-1)+fib_function(n-2)
}

fibs[n] = res
return
}

func main(){
fib_function(10)

for i := 0; i<10;i++{
fmt.Println(fibs[i])
}
}
```