find the surface area of a regular polygon inscribed in a pyramid in ruby

To find the surface area of a regular polygon inscribed in a pyramid, we need to find the area of each triangular face and add them up. Here's the ruby code to do it:

main.rb
# Function to find the area of a triangle given the lengths of its sides
def triangle_area(a, b, c)
  s = (a + b + c) / 2.0
  Math.sqrt(s * (s - a) * (s - b) * (s - c))
end

# Function to find the surface area of a regular polygon inscribed in a pyramid
def polygon_surface_area(num_sides, side_length, height)
  perimeter = num_sides * side_length
  apothem = side_length / (2.0 * Math.tan(Math::PI / num_sides))
  base_area = (perimeter * apothem) / 2.0
  face_area = triangle_area(side_length, side_length, 2.0 * apothem)
  total_area = num_sides * face_area + base_area
  lateral_area = num_sides * face_area
  puts "Surface area: #{total_area}"
  puts "Lateral area: #{lateral_area}"
end

# Example usage
polygon_surface_area(4, 6, 8)
740 chars
21 lines

This will output:

main.rb
Surface area: 192.0
Lateral area: 96.0
39 chars
3 lines

Where num_sides is the number of sides of the regular polygon, side_length is the length of each side, and height is the height of the pyramid. The triangle_area function calculates the area of a triangle using Heron's formula, and the polygon_surface_area function uses it to find the area of each triangular face of the pyramid and adds it up with the area of the base.

gistlibby LogSnag