Largest sphere that can be inscribed within a cube which is in turn inscribed within a right circular cone
Last Updated :
05 Aug, 2022
Given here is a right circular cone of radius r and perpendicular height h , which is inscribed in a cube which in turn is inscribed in a sphere, the task is to find the radius of the sphere.Examples:
Input: h = 5, r = 6
Output: 1.57306
Input: h = 8, r = 11
Output: 2.64156
Approach :
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float sphereSide(float h, float r)
{
if (h < 0 && r < 0)
return -1;
float R = ((h * r * sqrt(2)) / (h + sqrt(2) * r)) / 2;
return R;
}
int main()
{
float h = 5, r = 6;
cout << sphereSide(h, r) << endl;
return 0;
}
Java
import java.lang.Math;
class GFG
{
static float sphereSide(float h, float r)
{
if (h < 0 && r < 0)
return -1;
float R = (float)((h * r * Math.sqrt(2)) /
(h + Math.sqrt(2) * r)) / 2;
return R;
}
public static void main(String[] args)
{
float h = 5, r = 6;
System.out.println(sphereSide(h, r));
}
}
Python3
import math
def sphereSide(h, r):
if h < 0 and r < 0:
return -1
R = (((h * r * math.sqrt(2))) /
(h + math.sqrt(2) * r) / 2)
return R
h = 5; r = 6
print(sphereSide(h, r))
C#
using System;
class GFG
{
static float sphereSide(float h, float r)
{
if (h < 0 && r < 0)
return -1;
float R = (float)((h * r * Math.Sqrt(2)) /
(h + Math.Sqrt(2) * r)) / 2;
return R;
}
public static void Main()
{
float h = 5, r = 6;
Console.WriteLine(sphereSide(h, r));
}
}
PHP
<?php
function sphereSide($h, $r)
{
if ($h < 0 && $r < 0)
return -1;
$R = (($h * $r * sqrt(2)) /
($h + sqrt(2) * $r)) / 2;
return $R;
}
$h = 5; $r = 6;
echo(sphereSide($h, $r));
?>
Javascript
<script>
function sphereSide(h , r)
{
if (h < 0 && r < 0)
return -1;
var R = ((h * r * Math.sqrt(2)) /
(h + Math.sqrt(2) * r)) / 2;
return R;
}
var h = 5, r = 6;
document.write(sphereSide(h, r).toFixed(5));
</script>
Time Complexity: O(1)Auxiliary Space: O(1)
Share your thoughts in the comments
Add Your Comment
Please Login to comment...