LoginSignup
7
0

More than 3 years have passed since last update.

マルチスケールシミュレーション特論:第10回(Recursive)

Last updated at Posted at 2020-12-30

Fibonacci数列

再帰(Recursive)処理の練習に,Fibonacci数列の第n項を出力する関数fibを実装する.

fibonacci.rb
def fib(n)
  if n == 0
    return 0
  end

  if n == 1
    return 1
  end

  return fib(n-1) + fib(n-2)
end

前回作ったassertを使ってテストする

fibonacci.rb
require './assert'
[[0,0],[1,1],[2,1],[3,2],[4,3],
 [5,5],[6,8],[7,13],[8,21]].each do |index, expected|
  assert_equal(expected, fib(index))
end

参考文献

チャート式ruby-V(Recursive Fibonacci)


  • source ~/grad_members_20f/members/ryuta-kikuchi/qiita_articles/lecture10.org
7
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
7
0