Largest cube that can be inscribed within the sphere
Last Updated :
27 Jul, 2022
Given here is a sphere of radius r, the task is to find the side of the largest cube that can fit inside in it.
Examples:
Input: r = 8
Output: 9.2376
Input: r = 5
Output: 5.7735

Approach:
Side of the cube = a
Radius of the sphere = r
From the diagonal, it is clear that, diagonal of the cube = diameter of the sphere,
a?3 = 2r or, a = 2r/?3
Below is the implementation:
C++
#include <bits/stdc++.h>
using namespace std;
float largestCube(float r)
{
if (r < 0)
return -1;
float a = (2 * r) / sqrt(3);
return a;
}
int main()
{
float r = 5;
cout << largestCube(r) << endl;
return 0;
}
|
Java
import java.util.*;
class Solution{
static float largestCube(float r)
{
if (r < 0)
return -1;
float a = (2 * r) / (float)Math.sqrt(3);
return a;
}
public static void main(String args[])
{
float r = 5;
System.out.println( largestCube(r));
}
}
|
Python3
from math import sqrt
def largestCube(r):
if (r < 0):
return -1
a = (2 * r) / sqrt(3)
return a
if __name__ == '__main__':
r = 5
print("{0:.6}".format(largestCube(r)))
|
C#
using System;
class Solution{
static float largestCube(float r)
{
if (r < 0)
return -1;
float a = (2 * r) / (float)Math.Sqrt(3);
return a;
}
static void Main()
{
float r = 5;
Console.WriteLine( largestCube(r));
}
}
|
PHP
<?php
function largestCube($r)
{
if ($r < 0)
return -1;
$a = (float)((2 * $r) / sqrt(3));
return $a;
}
$r = 5;
echo largestCube($r);
?>
|
Javascript
<script>
function largestCube(r)
{
if (r < 0)
return -1;
var a = (2 * r) / Math.sqrt(3);
return a;
}
var r = 5;
document.write( largestCube(r).toFixed(5));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...