find the surface area of a regular polygon circumscribed around a pyramid in swift

To find the surface area of a regular polygon circumscribed around a pyramid, you need to calculate the area of each triangular face of the pyramid and add them up. Here is the swift code to do this:

main.swift
let numSides = 4 // number of sides of the polygon
let sideLength: Double = 2.0 // length of each side of the polygon
let apothem = sideLength / (2.0 * tan(Double.pi / Double(numSides))) // apothem of the polygon
let height = sqrt(pow(apothem, 2) + pow(sideLength, 2)) // height of each triangular face
let baseArea = pow(sideLength, 2) * Double(numSides) / (4.0 * tan(Double.pi / Double(numSides))) // area of the regular polygon base
let lateralSurfaceArea = Double(numSides) * sideLength * height / 2.0 // area of all triangular faces
let totalSurfaceArea = lateralSurfaceArea + baseArea // sum of all surface areas
619 chars
8 lines

In this code, numSides is the number of sides of the regular polygon, sideLength is the length of each side, apothem is the distance from the center of the polygon to the midpoint of each side (which will also be the slant height of each triangular face), height is the height of each triangular face (which we calculate using the Pythagorean theorem), baseArea is the area of the regular polygon base (which we calculate using the formula for the area of a regular polygon), lateralSurfaceArea is the area of all the triangular faces (which we calculate by multiplying the perimeter of the polygon by the height of each triangular face and dividing by 2), and totalSurfaceArea is the sum of the base and lateral surface areas.

gistlibby LogSnag