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.

Go言語 : 再帰(フィボナッチ数の計算)

Last updated at Posted at 2022-04-15

再帰

ある処理内部で、再びその処理自身を呼び出すような処理。

フィボナッチ数

2つ前の項と1つ前の項を足し合わせていくことでできる数。
自然界に多く見られる、数学的規則性。

Code

	var fibonacci func(n int) <-chan int
	// 何番目を求めるかを定義
	fibTarget := [5]int{10, 15, 20, 25, 30}

	// フィボナッチ数を求めるための無名関数を格納
	fibonacci = func(n int) <-chan int {
		result := make(chan int)

		// 無名関数によるゴルーチン
		go func() {
			// チャネルを閉じるための予約
			defer close(result)
			// 2以下の場合は必然的に1
			if n <= 2 {
				result <- 1
				return
			}
			// 再帰により、n-1番目を求める
			f1 := <-fibonacci(n-1)
			// 再帰により、n-2番目を求める
			f2 := <-fibonacci(n-2)
			// n-1番目とn-2番目を足し、フィボナッチ数を求める
			result <- f1 + f2
		}()

		return result
	}

	// ターゲットのフィボナッチ数を求める
	for _, f := range fibTarget {
		fib := <-fibonacci(f)
		fmt.Printf("No.%d fibonacci is %d \n", f, fib)
	}

Output Sample

~ $ go build -o main main.go
~ $ ./main
No.10 fibonacci is 55
No.15 fibonacci is 610
No.20 fibonacci is 6765
No.25 fibonacci is 75025
No.30 fibonacci is 832040

GitHub

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?