Longest rod that can be inserted within a right circular cylinder
Last Updated :
14 Mar, 2023
Given a right circular cylinder of height , & radius . The task is to find the length of the longest rod that can be inserted within it.
Examples:
Input : h = 4, r = 1.5
Output : 5
Input : h= 12, r = 2.5
Output : 13
Approach:
From the figure, it is clear that we can get the length of the rod by using pythagoras theorem, by treating the height of cylinder as perpendicular, diameter as base and length of rod as hypotenuse.
So, l2 = h2 + 4*r2.
Therefore,
l = ?(h2 + 4*r2)
Follow the below steps to implement the above idea:
- Check if the height h and radius r is negative. If either is negative, return -1 to indicate an error.
- Calculate the length of the rod using the formula sqrt(h^2 + 4r^2), and assign the result to the float variable l.
- Return the value of l.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float rod( float h, float r)
{
if (h < 0 && r < 0)
return -1;
float l = sqrt ( pow (h, 2) + 4 * pow (r, 2));
return l;
}
int main()
{
float h = 4, r = 1.5;
cout << rod(h, r) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
static float rod( float h, float r)
{
if (h < 0 && r < 0 )
return - 1 ;
float l = ( float )(Math.sqrt(Math.pow(h, 2 ) + 4 * Math.pow(r, 2 )));
return l;
}
public static void main (String[] args) {
float h = 4 ;
float r = 1 .5f;
System.out.print(rod(h, r));
}
}
|
Python 3
import math
def rod(h, r):
if (h < 0 and r < 0 ):
return - 1
l = (math.sqrt(math. pow (h, 2 ) +
4 * math. pow (r, 2 )))
return float (l)
h , r = 4 , 1.5
print (rod(h, r))
|
C#
using System;
class GFG
{
static float rod( float h, float r)
{
if (h < 0 && r < 0)
return -1;
float l = ( float )(Math.Sqrt(Math.Pow(h, 2) +
4 * Math.Pow(r, 2)));
return l;
}
public static void Main ()
{
float h = 4;
float r = 1.5f;
Console.WriteLine(rod(h, r));
}
}
|
PHP
<?php
function rod( $h , $r )
{
if ( $h < 0 && $r < 0)
return -1;
$l = sqrt(pow( $h , 2) + 4 * pow( $r , 2));
return $l ;
}
$h = 4; $r = 1.5;
echo rod( $h , $r ) . "\n" ;
?>
|
Javascript
<script>
function rod(h , r)
{
if (h < 0 && r < 0)
return -1;
var l = (Math.sqrt(Math.pow(h, 2) + 4 * Math.pow(r, 2)));
return l;
}
var h = 4;
var r = 1.5;
document.write(rod(h, r));
</script>
|
Time Complexity: O(logn)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...