Program to find the shortest distance between diagonal and edge skew of a Cube

Program to find the shortest distance between diagonal and edge skew of a Cube
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 = 2Output: 1.4142Explanation:Length of KL = A / √2Length of KL = 2 / 1.41 = 1.4142
Input: A = 3Output: 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
using namespace std;
  

float diagonalLength(float a)
{
    
    float L = a / sqrt(2);
  
    
    cout  

Output:

1.41421

Time Complexity: O(1)Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.