Member-only story
JavaScript Algorithm: Sum of Polygon Angles
Today, we write a function called sumPolygon
that will accept one integer, n
, as an argument.
You are given an n
-sided regular polygon. The goal of the function is to calculate and return the total sum of internal angles. We are not going to go into mathematical detail on finding polygon angles, but we do have a formula to help you find the sum:
(n - 2) * 180
Here are some examples:
sumPolygon(3) // 180
sumPolygon(4) // 360
sumPolygon(6) // 720
Using the examples, we get our result by plugging n
into our formula above:
(3 - 2) * 180 = 180
(4 - 2) * 180 = 360
(6 - 2) * 180 = 720
To write our function, all we have to do is return the result of the formula.
return (n - 2) * 180
Here is the rest of the code:
function sumPolygon(n){
return (n - 2) * 180;
}
If you find this algorithm helpful, check out my other JavaScript algorithm solution articles: