Given here is a frustum of height h, top-radius r & base-radius R, which inscribes a right circular cylinder which in turn inscribes a sphere . The task is to find the largest possible volume of this sphere.
Examples:
Input: r = 5, R = 8, h = 11
Output: 523.333
Input: r = 9, R = 14, h = 20
Output:3052.08

Approach: Let the height of the cylinder = H, radius of the sphere = x
We know, the height and radius of the cylinder inscribed within the frustum is equal to the height and top-radius of the frustum respectively(Please refer here).So the height of the cylinder = h, radius of the cylinder = r.
Also, radius of the sphere inscribed within a cylinder is equal to radius of the cylinder(Please refer here), so x = r.
So, volume of the sphere, V = 4*?*r^3/3.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float sph( float r, float R, float h)
{
if (r < 0 && R < 0 && h < 0)
return -1;
float x = r;
float V = (4 * 3.14 * pow (r, 3)) / 3;
return V;
}
int main()
{
float r = 5, R = 8, h = 11;
cout << sph(r, R, h) << endl;
return 0;
}
|
Java
import java.lang.Math;
class gfg
{
static float sph( float r, float R, float h)
{
if (r < 0 && R < 0 && h < 0 )
return - 1 ;
float x = r;
float V = ( float )( 4 * 3 .14f * Math.pow(r, 3 )) / 3 ;
return V;
}
public static void main(String[] args)
{
float r = 5 , R = 8 , h = 11 ;
System.out.println(sph(r, R, h));
}
}
|
Python3
import math as mt
def sph(r, R, h):
if (r < 0 and R < 0 and h < 0 ):
return - 1
x = r
V = ( 4 * 3.14 * pow (r, 3 )) / 3
return V
r, R, h = 5 , 8 , 11
print (sph(r, R, h))
|
C#
using System;
class gfg
{
static float sph( float r, float R, float h)
{
if (r < 0 && R < 0 && h < 0)
return -1;
float x = r;
float V = ( float )(4 * 3.14f *
Math.Pow(r, 3)) / 3;
return V;
}
public static void Main()
{
float r = 5, R = 8, h = 11;
Console.WriteLine(sph(r, R, h));
}
}
|
PHP
<?php
function sph( $r , $R , $h )
{
if ( $r < 0 && $R < 0 && $h < 0)
return -1;
$x = $r ;
$V = (4 * 3.14 * pow( $r , 3)) / 3;
return $V ;
}
$r = 5;
$R = 8;
$h = 11;
echo sph( $r , $R , $h );
#This Code is contributed by ajit..
?>
|
Javascript
<script>
function sph(r , R , h)
{
if (r < 0 && R < 0 && h < 0)
return -1;
var x = r;
var V = ((4 * 3.14 * Math.pow(r, 3)) / 3);
return V;
}
var r = 5, R = 8, h = 11;
document.write(sph(r, R, h).toFixed(5));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)