Area of a n-sided regular polygon with given side length
Last Updated :
25 Jun, 2022
Given a regular polygon of N sides with side length a. The task is to find the area of the polygon.
Examples:
Input : N = 6, a = 9
Output : 210.444
Input : N = 7, a = 8
Output : 232.571

Approach: In the figure above, we see the polygon can be divided into N equal triangles. Looking into one of the triangles, we see that the whole angle at the center can be divided into = 360/N
So, angle t = 180/n
Now, tan(t) = a/2*h
So, h = a/(2*tan(t))
Area of each triangle = (base * height)/2 = a * a/(4*tan(t))
So, area of the polygon,
A = n * (area of one triangle) = a2 * n/(4tan t)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float polyarea(float n, float a)
{
if (a < 0 && n < 0)
return -1;
float A = (a * a * n) / (4 * tan((180 / n) * 3.14159 / 180));
return A;
}
int main()
{
float a = 9, n = 6;
cout << polyarea(n, a) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
static float polyarea(float n, float a)
{
if (a < 0 && n < 0)
return -1;
float A = (a * a * n) /(float) (4 * Math.tan((180 / n) * 3.14159 / 180));
return A;
}
public static void main (String[] args) {
float a = 9, n = 6;
System.out.println( polyarea(n, a));
}
}
|
Python3
from math import tan
def polyarea(n, a):
if (a < 0 and n < 0):
return -1
A = (a * a * n) / (4 * tan((180 / n) *
3.14159 / 180))
return A
if __name__ == '__main__':
a = 9
n = 6
print('{0:.6}'.format(polyarea(n, a)))
|
C#
using System;
class GFG
{
static float polyarea(float n, float a)
{
if (a < 0 && n < 0)
return -1;
float A = (a * a * n) / (float)(4 * Math.Tan((180 / n) *
3.14159 / 180));
return A;
}
public static void Main ()
{
float a = 9, n = 6;
Console.WriteLine(polyarea(n, a));
}
}
|
PHP
<?php
function polyarea($n, $a)
{
if ($a < 0 && $n < 0)
return -1;
$A = ($a * $a * $n) / (4 * tan((180 / $n) *
3.14159 / 180));
return $A;
}
$a = 9 ;
$n = 6 ;
echo round(polyarea($n, $a), 3);
?>
|
Javascript
<script>
function polyarea(n , a)
{
if (a < 0 && n < 0)
return -1;
var A = (a * a * n) / (4 * Math.tan((180 / n) * 3.14159 / 180));
return A;
}
var a = 9, n = 6;
document.write( polyarea(n, a).toFixed(5));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Please Login to comment...