Horje
Largest square that can be inscribed in a semicircle

Given a semicircle with radius r, we have to find the largest square that can be inscribed in the semicircle, with base lying on the diameter.

Examples: 

Input: r = 5
Output: 20

Input: r = 8
Output: 51.2

Approach: Let r be the radius of the semicircle & a be the side length of the square
From the figure we can see that, centre of the circle is also the midpoint of the base of the square. So in the right angled triangle AOB, from Pythagoras Theorem:

a^2 + (a/2)^2 = r^2
5*(a^2/4) = r^2
a^2 = 4*(r^2/5) i.e. area of the square
 

Below is the implementation of the above approach:  

C++

<?php
// PHP Program to find the
// biggest square which can be
// inscribed within the semicircle
 
// Function to find the area
// of the square
function squarearea($r)
{
 
    // the radius cannot be negative
    if ($r < 0)
        return -1;
 
    // area of the square
    $a = 4 * (pow($r, 2) / 5);
 
    return $a;
}
 
// Driver code
$r = 5;
echo squarearea($r);
 
// This code is contributed
// by Shivi_Aggarwal
?>

Javascript

<script>
 
// javascript Program to find the biggest square
// which can be inscribed within the semicircle
 
// Function to find the area
// of the square
function squarearea(r)
{
 
    // the radius cannot be negative
    if (r < 0)
        return -1;
 
    // area of the square
    var a = 4 * (Math.pow(r, 2) / 5);
 
    return a;
}
 
// Driver code
var r = 5;
document.write( squarearea(r));
 
// This code contributed by Princi Singh
 
</script>

Output: 

20

 

Time Complexity: O(1)

Auxiliary Space: O(1)




Reffered: https://www.geeksforgeeks.org


DSA

Related
Find the sum of infinite series 1^2.x^0 + 2^2.x^1 + 3^2.x^2 + 4^2.x^3 +....... Find the sum of infinite series 1^2.x^0 + 2^2.x^1 + 3^2.x^2 + 4^2.x^3 +.......
Largest trapezoid that can be inscribed in a semicircle Largest trapezoid that can be inscribed in a semicircle
Minimum Players required to win the game Minimum Players required to win the game
Area of a largest square fit in a right angle triangle Area of a largest square fit in a right angle triangle
Find the sum of series 0.X + 0.XX + 0.XXX +... upto k terms Find the sum of series 0.X + 0.XX + 0.XXX +... upto k terms

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
10