dongyipa0028 2014-08-25 17:37
浏览 56
已采纳

斐波那契封闭中

I am following the go tour on their official website and I have been asked to write a Fibonacci generator. Here it is:

 package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
    first := 0
    second := 0
    return func() int{
        if(first == 0) {
         first = 1
         second = 1
         return 0
        }else {
            current := first   
            firstc := second
            second = first + second
            first = firstc
            return current
        }



    }
}

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

It works. However I consider it very ugly and I'm sure there has to be a better solution. I have been thinking about posting this on the code-review however since I'm asking for a better approach I thought this is the right place to post it.

Is there a better way to write this code?

Here is the task:

Implement a fibonacci function that returns a function (a closure) that returns successive fibonacci numbers.

  • 写回答

7条回答 默认 最新

  • douhui7136 2014-08-25 17:50
    关注

    My favorite clean way to implement iterating through the Fibonacci numbers is to use first as fi - 1, and second as fi. The Fibonacci equation states that:

    fi + 1 = fi + fi - 1

    Except when we write this in code, in the next round we're incrementing i. So we're effectively doing:

    fnext i = fcurrent i + fcurrent i - 1

    and

    fnext i - 1 = fcurrent i - 1

    The way I like to implement this in code is:

    first, second = second, first + second
    

    The first = second part corresponds to updating fnext i - 1 = fcurrent i - 1, and the second = first + second part corresponds to updating fnext i = fcurrent i + fcurrent i - 1.

    Then all we have left to do is return the old value of first, so we'll store it in a temp variable out of the way before doing the update. In total, we get:

    // fibonacci returns a function that returns
    // successive fibonacci numbers from each
    // successive call
    func fibonacci() func() int {
        first, second := 0, 1
        return func() int {
            ret := first
            first, second = second, first+second
            return ret
        }
    }
    

    See it in action on the Go Playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂