Given a perimeter P and area A, the task is to calculate the maximum volume that can be made in form of cuboid from the given perimeter and surface area.
Examples :
Input: P = 24, A = 24
Output: 8
Input: P = 20, A = 14
Output: 3
Approach: For a given perimeter of cuboid we have P = 4(l+b+h) —(i),
for given area of cuboid we have A = 2 (lb+bh+lh) —(ii).
Volume of cuboid is V = lbh
Volume is dependent on 3 variables l, b, h. Lets make it dependent on only length.
as V = lbh,
=> V = l (A/2-(lb+lh)) {from equation (ii)}
=> V = lA/2 – l2(b+h)
=> V = lA/2 – l2(P/4-l) {from equation (i)}
=> V = lA/2 – l2P/4 + l3 —-(iii)
Now differentiate V w.r.t l for finding maximum of volume.
dV/dl = A/2 – lP/2 + 3l2
After solving the quadratic in l we have l = (P – (P2-24A)1/2) / 12
Substituting value of l in (iii), we can easily find the maximum volume.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float maxVol( float P, float A)
{
float l = (P - sqrt (P * P - 24 * A)) / 12;
float V = l * (A / 2.0 - l * (P / 4.0 - l));
return V;
}
int main()
{
float P = 20, A = 16;
cout << maxVol(P, A);
return 0;
}
|
Java
import java.util.*;
class Geeks {
static float maxVol( float P, float A)
{
float l
= ( float )(P - Math.sqrt(P * P - 24 * A)) / 12 ;
float V
= ( float )(l * (A / 2.0 - l * (P / 4.0 - l)));
return V;
}
public static void main(String args[])
{
float P = 20 , A = 16 ;
System.out.println(maxVol(P, A));
}
}
|
Python3
from math import sqrt
def maxVol(P, A):
l = (P - sqrt(P * P - 24 * A)) / 12
V = l * (A / 2.0 - l * (P / 4.0 - l))
return V
if __name__ = = '__main__' :
P = 20
A = 16
print (maxVol(P, A))
|
C#
using System;
class GFG {
static float maxVol( float P, float A)
{
float l
= ( float )(P - Math.Sqrt(P * P - 24 * A)) / 12;
float V
= ( float )(l * (A / 2.0 - l * (P / 4.0 - l)));
return V;
}
public static void Main()
{
float P = 20, A = 16;
Console.WriteLine(maxVol(P, A));
}
}
|
PHP
<?php
function maxVol( $P , $A )
{
$l = ( $P - sqrt( $P * $P - 24 * $A )) / 12;
$V = $l * ( $A / 2.0 - $l *
( $P / 4.0 - $l ));
return $V ;
}
$P = 20;
$A = 16;
echo maxVol( $P , $A );
?>
|
Javascript
<script>
function maxVol( P, A)
{
let l = (P - Math.sqrt(P * P - 24 * A)) / 12;
let V = l * (A / 2.0 - l * (P / 4.0 - l));
return V;
}
let P = 20, A = 16;
document.write(maxVol(P, A).toFixed(5));
</script>
|
Time Complexity: O(logn) as sqrt function is being used, time complexity of sqrt is logn
Auxiliary Space: O(1)