1
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 3 years have passed since last update.

R10.org

Last updated at Posted at 2020-12-23

!Mac OS X-10.15.7 !ruby-2.7.1p83

第10回

チャート式Rubyの第5回目

Fibonacci数列

fib(n) = fib(n-1)+fib(n-2)
0 1 1 2 3 5 8 13 21 ...

上記のようなFibonacci数列を再帰で求める。

assert_equal.rb

require 'colorize'

def assert_equal(expected, result)
  if expected == result
    puts 'true'.blue
  else
    puts 'false'.red
  end
end

assert_equal(1, 1)
assert_equal(1, 2)
def fib(n)
  return 0 if n==0
  return 1 if n==1
  return fib(n-1) + fib(n-2)
end

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

上記のコードを実行してみる

 ruby fib.rb
true
false
true

true

true

true

true

true

true

true

true

true

参考サイト

チャート式ruby-Ⅴ


  • source ~/grad_members_20f/members/skona/memo/R10.org
1
0
1

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
1
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?