golang 练习:斐波纳契闭合

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang 练习:斐波纳契闭合相关的知识,希望对你有一定的参考价值。

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
    idx, beforeLastN, lastN := 0, 0, 1
    return func() int {
        if (idx == 0) {
            idx++
            return beforeLastN
        }
        if (idx == 1) {
            idx++
            return lastN
        }
        sum := beforeLastN + lastN
        beforeLastN = lastN
        lastN = sum
        return sum
    }
}

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

PHP 斐波纳契数

&lt;?php
    /*
    Copyright (c) 2008, reusablecode.blogspot.com; some rights reserved.
    
    This work is licensed under the Creative Commons Attribution License. To view
    a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or
    send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California
    94305, USA.
    */
    
    // Get Fibonacci number
    function fib($x)
    {
        $fibArray[0] = 0;
        $fibArray[1] = 1;
        
        for($i = 2; $i &lt;= $x; $i++)
        {
            $fibArray[$i] = $fibArray[$i - 1] + $fibArray[$i - 2];
        }
        
        return $fibArray[$x];
    }
?&gt;

以上是关于golang 练习:斐波纳契闭合的主要内容,如果未能解决你的问题,请参考以下文章

斐波纳契数列

LintCode-查找斐波纳契数列中第 N 个数

1807. 斐波纳契数列简单

LintCode Python 入门级题目 斐波纳契数列

python之斐波纳契数列

「递归」求第n个斐波纳契数