0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

「A Tour of Go」 の Exercise: Fibonacci closure を解きました

Last updated at Posted at 2022-08-02

引き続き、Goの公式のチュートリアル「A Tour of Go」を読み進めています。当記事は、関数の一種「クロージャー」に関する練習問題「Exercise: Fibonacci closure」を解いた記録です。

コード

package main

import "fmt"

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

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

解説

フィボナッチ数列はご存知かと思います。f(n)=f(n-1)+f(n-2) (n>=0)で表される数列です。f(0)=0 f(1)=1が与えられると、

f(2) = f(0)+f(1) = 1, f(3) = f(2)+f(1) = 2, f(4) = f(3)+f(2) = 3,
f(5) = f(3)+f(2) = 5, f(6) = f(4)+f(5) = 8, f(7) = f(5)+f(6) = 13 ...

という感じで直前の2つの値が結果となります。なので直前の値の和を結果とし、結果を求めたら右に1つずれるイメージで変数を更新すれば上手く行きます。

最後に

対して解説することもありませんでしたが、同じような境遇の方のご参考になれば幸いです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?