find the area of a regular polygon circumscribed around a circle in swift

To find the area of a regular polygon circumscribed around a circle, you will need to know the length of one side of the polygon, the number of sides in the polygon, and the radius of the circle.

Here's the formula to calculate the area of a regular polygon given that you have the length of the side (s) of the polygon and the number of sides (n):

main.swift
let area = (0.25 * n * s * s) / tan(.pi / Double(n))
53 chars
2 lines

And to find the radius of the circle, you can use the following formula, where s is the length of one side of the polygon:

main.swift
let radius = s / (2 * sin(.pi / Double(n)))
44 chars
2 lines

Put it all together, you can write a function like this:

main.swift
func areaOfPolygonCircumscribedAroundCircle(numberOfSides n: Int, lengthOfSide s: Double) -> Double {
    let radius = s / (2 * sin(.pi / Double(n)))
    let area = (0.25 * n * s * s) / tan(.pi / Double(n))
    return area
}
225 chars
6 lines

Now you can call this function and pass in the number of sides and length of one side of your polygon to find its area:

main.swift
let area = areaOfPolygonCircumscribedAroundCircle(numberOfSides: 6, lengthOfSide: 5.0)
print("The area of the hexagon is \(area)")
131 chars
3 lines

gistlibby LogSnag