find the nth triangular number in ruby

To find the nth triangular number in Ruby, we can either use a loop or a formula.

Using a loop:

main.rb
def triangular_loop(n)
  sum = 0
  (1..n).each do |i|
    sum += i
  end
  return sum
end

puts triangular_loop(5) #=> 15
122 chars
10 lines

Using a formula:

main.rb
def triangular_formula(n)
  return (n*(n+1))/2
end

puts triangular_formula(5) #=> 15
86 chars
6 lines

Both functions take one argument n, which represents the index of the triangular number we want to find. The first function (triangular_loop) loops through the numbers from 1 up to n, adding each number to a sum. The second function (triangular_formula) uses a formula to calculate the triangular number directly.

Both functions return the nth triangular number. In this example, calling either function with an argument of 5 will return 15, which is the 5th triangular number.

gistlibby LogSnag