Given a square of side length ‘a’, the task is to find the side length of the biggest octagon that can be inscribed within it.
Examples:
Input: a = 4
Output: 1.65685
Input: a = 5
Output: 2.07107

Approach:
=> From the figure, it can be seen that, side length of the Octagon = b
=> Also since the polygons are regular, therefore 2*x + b = a
=> From the right angled triangle, x^2 + x^2 = b^2
=> Hence, x = b/?2,
=> So, ?2b + b = a
=> Therefore, b = a/(?2 +1)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float octaside( float a)
{
if (a < 0)
return -1;
float s = a / ( sqrt (2) + 1);
return s;
}
int main()
{
float a = 4;
cout << octaside(a) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
static double octaside( double a)
{
if (a < 0 )
return - 1 ;
double s = a / (Math.sqrt( 2 ) + 1 );
return s;
}
public static void main (String[] args) {
double a = 4 ;
System.out.println( octaside(a));
}
}
|
Python3
from math import sqrt
def octaside(a):
if a < 0 :
return - 1
s = a / (sqrt( 2 ) + 1 )
return s
if __name__ = = '__main__' :
a = 4
print ( "{0:.6}" . format (octaside(a)))
|
C#
using System;
class GFG
{
static double octaside( double a)
{
if (a < 0)
return -1;
double s = a / (Math.Sqrt(2) + 1);
return s;
}
static public void Main ()
{
double a = 4;
Console.WriteLine( octaside(a));
}
}
|
PHP
<?php
function octaside( $a )
{
if ( $a < 0)
return -1;
$s = $a / (sqrt(2) + 1);
return $s ;
}
$a = 4;
echo octaside( $a );
?>
|
Javascript
<script>
function octaside(a)
{
if (a < 0)
return -1;
var s = a / (Math.sqrt(2) + 1);
return s;
}
var a = 4;
document.write( octaside(a).toFixed(5));
</script>
|
Time Complexity: O(1) since no loop is used the algorithm takes up constant time to perform the operations
Space Complexity: O(1) since no extra array is used so the space taken by the algorithm is constant
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
11 Aug, 2022
Like Article
Save Article