Largest right circular cylinder within a cube
Given a cube of side length a. The task is to find the volume of biggest right circular cylinder that can be inscribed within it.
Examples:
Input : a = 4
Output : 50.24
Input : a = 5
Output : 98.125
Approach:
Let:
- The height of the cylinder is h.
- Radius of the cylinder be r.
From the diagram it is clear that:
- The height of the cylinder = side of cube
- Radius of the cylinder = side of the cube/2
So,
h = a
r = a/2
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float findVolume( float a)
{
if (a < 0)
return -1;
float r = a / 2;
float h = a;
float V = 3.14 * pow (r, 2) * h;
return V;
}
int main()
{
float a = 5;
cout << findVolume(a) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
static float findVolume( float a)
{
if (a < 0 )
return - 1 ;
float r = a / 2 ;
float h = a;
float V = ( float )( 3.14 * Math.pow(r, 2 ) * h);
return V;
}
public static void main (String[] args) {
float a = 5 ;
System.out.print(findVolume(a));
}
}
|
Python3
def findVolume(a) :
if (a < 0 ) :
return - 1
r = a / 2
h = a
V = 3.14 * pow (r, 2 ) * h
return V
if __name__ = = "__main__" :
a = 5
print (findVolume(a))
|
C#
using System;
class GFG {
static float findVolume( float a)
{
if (a < 0)
return -1;
float r = a / 2;
float h = a;
float V = ( float )(3.14 * Math.Pow(r, 2) * h);
return V;
}
public static void Main () {
float a = 5;
Console.WriteLine(findVolume(a));
}
}
|
PHP
<?php
function findVolume( $a )
{
if ( $a < 0)
return -1;
$r = $a / 2;
$h = $a ;
$V = 3.14 * pow( $r , 2) * $h ;
return $V ;
}
$a = 5;
echo findVolume( $a ) . "\n" ;
|
Javascript
<script>
function findVolume(a)
{
if (a < 0)
return -1;
var r = a / 2;
var h = a;
var V = (3.14 * Math.pow(r, 2) * h);
return V;
}
var a = 5;
document.write(findVolume(a));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
20 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...