find the nth octagonal number in ruby

math, sequence, number theory, integer, function

Method to find the nth octagonal number

def octagonal_number(n) n * (3 * n - 2) end

Example to find the 5th Octagonal number

puts octagonal_number(5) #=> 141

main.rb

In the code above, we define a method `octagonal_number` that takes an integer `n` as an argument and returns the nth octagonal number. 

The formula for finding the nth octagonal number is `n(3n-2)`. We implement this formula inside the method and return the result. 

In the example, we call the method with an argument of 5 to find the 5th octagonal number and print the result, which is 141.
397 chars
7 lines

related categories

gistlibby LogSnag