find the nth lucas number in ruby

To find the nth Lucas Number in Ruby, you can use an iterative approach or a recursive approach.

Using iterative approach:

main.rb
def lucas_number_iterative(n)
  return 2 if n == 0
  return 1 if n == 1

  ln = Array.new(n + 1)
  ln[0] = 2
  ln[1] = 1

  (2..n).each do |i|
    ln[i] = ln[i - 1] + ln[i - 2]
  end

  return ln[n]
end
203 chars
15 lines

Using recursive approach:

main.rb
def lucas_number_recursive(n)
  return 2 if n == 0
  return 1 if n == 1

  return lucas_number_recursive(n - 1) + lucas_number_recursive(n - 2)
end
148 chars
7 lines

Both of these methods will find the nth Lucas Number. You can test them by calling them with an integer argument:

main.rb
puts lucas_number_iterative(5) #=> 11
puts lucas_number_recursive(5) #=> 11
76 chars
3 lines

gistlibby LogSnag