Given an integer A, denoting the length of a cube, the task is to find the shortest distance between the diagonal of a cube and an edge skew to it i.e. KL in the below figure.

Examples :
Input: A = 2
Output: 1.4142
Explanation:
Length of KL = A / ?2
Length of KL = 2 / 1.41 = 1.4142
Input: A = 3
Output: 2.1213
Approach: The idea to solve the problem is based on the following mathematical formula:
Let’s draw a perpendicular from K to down face of cube as Q.
Using Pythagorean Theorem in triangle QKL,
KL2 = QK2 + QL2
l2 = (a/2)2 + (a/2)2
l2 = 2 * (a/2)2
l = a / sqrt(2)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float diagonalLength( float a)
{
float L = a / sqrt (2);
cout << L;
}
int main()
{
float a = 2;
diagonalLength(a);
return 0;
}
|
Java
class GFG {
static void diagonalLength( float a)
{
float L = a / ( float )Math.sqrt( 2 );
System.out.println(L);
}
public static void main(String[] args)
{
float a = 2 ;
diagonalLength(a);
}
}
|
Python3
from math import sqrt
def diagonalLength(a):
L = a / sqrt( 2 )
print (L)
a = 2
diagonalLength(a)
|
C#
using System;
class GFG {
static void diagonalLength( float a)
{
float L = a / ( float )Math.Sqrt(2);
Console.Write(L);
}
public static void Main()
{
float a = 2;
diagonalLength(a);
}
}
|
PHP
<?php
function diagonalLength( $a )
{
$L = $a / sqrt(2);
# Print the required distance
echo $L ;
}
$a = 2;
diagonalLength( $a );
?>
|
Javascript
<script>
function diagonalLength( a)
{
let L = a / Math.sqrt(2);
document.write( L.toFixed(5));
}
let a = 2;
diagonalLength(a);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
17 Mar, 2021
Like Article
Save Article