[RUBY] Special Lecture on Multiscale Simulation: 10th (Recursive)

Fibonacci sequence

To practice recursive processing, we implement a function fib that outputs the nth term of the Fibonacci sequence.

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

Test using the assert you made last time

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

References

Chart type ruby-V (Recursive Fibonacci)


Recommended Posts

Special Lecture on Multiscale Simulation: 10th (Recursive)
Special Lecture on Multi-Scale Simulation: 11th (class)
Special Lecture on Multiscale Simulation: 8th (assert)
Special Lecture on Multi-Scale Simulation: I tried to summarize the 8th
Special Lecture on Multi-Scale Simulation: I tried to summarize the 7th
Multiscale simulation 11