Diagonal of a Regular Hexagon
Last Updated :
25 Jun, 2022
Given an integer a which is the side of a regular hexagon, the task is to find and print the length of its diagonal.
Examples:
Input: a = 6
Output: 10.38
Input: a = 9
Output: 15.57
Approach: We know that the sum of interior angles of a polygon = (n – 2) * 180 where, n is the number of sides of the polygon.
So, sum of interior angles of a hexagon = 4 * 180 = 720 and each interior angle will be 120.
Now, we have to find BC = 2 * x. If we draw a perpendicular AO on BC, we will see that the perpendicular bisects BC in BO and OC, as triangles AOB and AOC are congruent to each other.
So, in triangle AOB, sin(60) = x / a i.e. x = 0.866 * a
Therefore, diagonal length will be 2 * x i.e. 1.73 * a.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float hexDiagonal( float a)
{
if (a < 0)
return -1;
float d = 1.73 * a;
return d;
}
int main()
{
float a = 9;
cout << hexDiagonal(a) << endl;
return 0;
}
|
Java
public class GFG
{
static double hexDiagonal( float a)
{
if (a < 0 )
return - 1 ;
double d = ( double ) 1.73 * a;
return d;
}
public static void main(String []args)
{
float a = 9 ;
System.out.println(hexDiagonal(a)) ;
}
}
|
Python3
def hexDiagonal(a):
if (a < 0 ):
return - 1 ;
d = 1.73 * a;
return d;
a = 9 ;
print (hexDiagonal(a));
|
C#
using System ;
public class GFG
{
static double hexDiagonal( float a)
{
if (a < 0)
return -1;
double d = ( double )1.73 * a;
return d;
}
public static void Main()
{
float a = 9;
Console.WriteLine(hexDiagonal(a)) ;
}
}
|
PHP
<?php
function hexDiagonal( $a )
{
if ( $a < 0)
return -1;
$d = 1.73 * $a ;
return $d ;
}
$a = 9;
echo hexDiagonal( $a ), "\n" ;
?>
|
Javascript
<script>
function hexDiagonal(a)
{
if (a < 0)
return -1;
var d = 1.73 * a;
return d;
}
var a = 9;
document.write(hexDiagonal(a)) ;
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...