Largest cube that can be inscribed within a right circular cone
Last Updated :
28 Aug, 2022
Given a right circular cone of radius r and perpendicular height h. We have to find the side length of the biggest cube that can be inscribed within it.
Examples:
Input : h = 5, r = 6
Output : 3.14613
Input : h = 8, r = 12
Output : 5.43698
Approach:
Let, side of the cube = a.
From the diagram, we can clearly understand using the properties of triangles: BC/AB = DE/AD.
Therefore,
r/h = (a/?2)/(h-a)
or, a = h*r?2/(h+?2*r)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float cubeSide( float h, float r)
{
if (h < 0 && r < 0)
return -1;
float a = (h * r * sqrt (2)) / (h + sqrt (2) * r);
return a;
}
int main()
{
float h = 5, r = 6;
cout << cubeSide(h, r) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
static float cube( float h, float r)
{
if (h < 0 && r < 0 )
return - 1 ;
float a = (h * r * ( float )Math.sqrt( 2 )) / (h + ( float )Math.sqrt( 2 ) * r);
return a;
}
public static void main (String[] args) {
float h = 5 , r = 6 ;
System.out.println( cube(h, r));
}
}
|
Python 3
import math
def cubeSide(h, r):
if (h < 0 and r < 0 ):
return - 1
a = ((h * r * math.sqrt( 2 )) /
(h + math.sqrt( 2 ) * r))
return a
h = 5 ; r = 6 ;
print (cubeSide(h, r), "\n" )
|
C#
using System;
class GFG
{
static float cube( float h, float r)
{
if (h < 0 && r < 0)
return -1;
float a = (h * r * ( float )Math.Sqrt(2)) /
(h + ( float )Math.Sqrt(2) * r);
return a;
}
public static void Main ()
{
float h = 5, r = 6;
Console.Write( cube(h, r));
}
}
|
PHP
<?php
function cubeSide( $h , $r )
{
if ( $h < 0 && $r < 0)
return -1;
$a = ( $h * $r * sqrt(2)) /
( $h + sqrt(2) * $r );
return $a ;
}
$h = 5;
$r = 6;
echo cubeSide( $h , $r );
?>
|
Javascript
<script>
function cube(h , r)
{
if (h < 0 && r < 0)
return -1;
var a = (h * r * Math.sqrt(2)) / (h + Math.sqrt(2) * r);
return a;
}
var h = 5, r = 6;
document.write( cube(h, r).toFixed(5));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1), since no extra space has been taken.
Share your thoughts in the comments
Please Login to comment...