Length of the Diagonal of the Octagon
Last Updated :
25 Aug, 2022
Given here is a regular octagon of side length a, the task is to find the length of it’s diagonal.
Examples:
Input: a = 4
Output: 10.4525
Input: a = 5
Output: 13.0656
Approach: From the diagram it is clear that,
AB^2 + BC^2 = AC^2
here, in triangle AED,
b^2 + b^2 = a^2
or, b=a/?2(Please refer)
So, AB = a + 2b = a + ?2a
and, BC = a
So, diagonal AC = a?(4 + 2?2)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float octadiagonal( float a)
{
if (a < 0)
return -1;
return a * sqrt (4 + (2 * sqrt (2)));
}
int main()
{
float a = 4;
cout << octadiagonal(a) << endl;
return 0;
}
|
Java
import java.util.*;
class solution
{
static double octadiagonal( double a)
{
if (a < 0 )
return - 1 ;
return a * Math.sqrt( 4 + ( 2 * Math.sqrt( 2 )));
}
public static void main(String args[])
{
double a = 4 ;
System.out.println( octadiagonal(a));
}
}
|
Python3
import math
def octadiagonal(a):
if (a < 0 ):
return - 1 ;
return a * math.sqrt( 4 + ( 2 * math.sqrt( 2 )))
if __name__ = = '__main__' :
a = 4
print (octadiagonal(a))
|
C#
using System;
class GFG
{
static double octadiagonal( double a)
{
if (a < 0)
return -1;
return a * Math.Sqrt(4 +
(2 * Math.Sqrt(2)));
}
public static void Main()
{
double a = 4;
Console.WriteLine(octadiagonal(a));
}
}
|
PHP
<?php
function octadiagonal( $a )
{
if ( $a < 0)
return -1;
return $a * sqrt(4 + (2 * sqrt(2)));
}
$a = 4;
echo octadiagonal( $a ) ;
?>
|
Javascript
<script>
function octadiagonal(a)
{
if (a < 0)
return -1;
return a * Math.sqrt(4 + (2 * Math.sqrt(2)));
}
var a = 4;
document.write( octadiagonal(a).toFixed(5));
</script>
|
Time complexity: O(1), since there is no loop or recursion.
Auxiliary Space: O(1), since no extra space has been taken.
Share your thoughts in the comments
Please Login to comment...