Find the diagonal of the Cube
Given a side of the cube a. The task is to find the length of the diagonal of the cube.
Examples:
Input : a = 3
Output : 5.19615
Input : a = 6
Output : 10.3923
Formula :
Length of diagonal of the cube = sqrt(3) * side
Proof :
Use Pythagorean Theorem,
In triangle CED,
CE2 = CD2 + DE2
l2 = a2 + a2 ———>(1)
In triangle CFE,
CF2 = CE2 + EF2
L2 = l2 + a2
use l2 value from equation(1),
L2 = a2 + a2 + a2
= 3*a2
L = sqrt(3) * a
C++
#include <bits/stdc++.h>
using namespace std;
float diagonal_length( float a)
{
float L;
L = a * sqrt (3);
return L;
}
int main()
{
float a = 5;
cout << diagonal_length(a);
return 0;
}
|
Java
class GFG
{
static float diagonal_length( float a)
{
float L;
L = a * ( float )Math.sqrt( 3 );
return L;
}
public static void main (String[] args)
{
float a = 5 ;
System.out.println(diagonal_length(a));
}
}
|
Python3
from math import sqrt
def diagonal_length(a):
L = 0
L = a * sqrt( 3 )
return L
a = 5
print (diagonal_length(a))
|
C#
using System;
class GFG
{
static float diagonal_length( float a)
{
float L;
L = a * ( float )Math.Sqrt(3);
return L;
}
public static void Main()
{
float a = 5;
Console.Write(diagonal_length(a));
}
}
|
PHP
<?php
function diagonal_length( $a )
{
$L ;
$L = $a * sqrt(3);
return $L ;
}
$a = 5;
echo diagonal_length( $a );
?>
|
Javascript
<script>
function diagonal_length( a)
{
let L;
L = a * Math.sqrt(3);
return L;
}
let a = 5;
document.write(diagonal_length(a).toFixed(5));
</script>
|
Time Complexity: O(1), as using sqrt(3) will take constant operations.
Auxiliary Space: O(1)
Last Updated :
23 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...