Hot For Coding
Golang实现斐波那契

JavaScript,Python和PHP实现的都写过了,今天用Go再来一下

什么是斐波那契

斐波那契数列指的是这样一个数列 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368........
这个数列从第3项开始,每一项都等于前两项之和

代码实现

package main

import (
  "fmt"
)

var (
  v1 = 0
  v2 = 0
)

func fibonacci() int {

  if v1 == 0 {
    v1 = 1
  } else {
    v1, v2 = v1+v2, v1
  }

  return v1
}

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

Output:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55

TITLE: Golang实现斐波那契

LINK: https://www.qttc.net/265_golang_fibonacci.html

NOTE: 转载内容请注明出处