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++
#include <bits/stdc++.h>
using namespace std;
float squarearea( float r)
{
if (r < 0)
return -1;
float a = 4 * ( pow (r, 2) / 5);
return a;
}
int main()
{
float r = 5;
cout << squarearea(r) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
static float squarearea( float r)
{
if (r < 0 )
return - 1 ;
float a = 4 * ( float )(Math.pow(r, 2 ) / 5 );
return a;
}
public static void main (String[] args) {
float r = 5 ;
System.out.println( squarearea(r));
}
}
|
Python3
def squarearea(r):
if (r < 0 ):
return - 1
a = 4 * ( pow (r, 2 ) / 5 )
return a
if __name__ = = "__main__" :
r = 5
print ( int (squarearea(r)))
|
C#
using System;
class GFG
{
static float squarearea( float r)
{
if (r < 0)
return -1;
float a = 4 * ( float )(Math.Pow(r, 2) / 5);
return a;
}
public static void Main ()
{
float r = 5;
Console.WriteLine(squarearea(r));
}
}
|
PHP
<?php
function squarearea( $r )
{
if ( $r < 0)
return -1;
$a = 4 * (pow( $r , 2) / 5);
return $a ;
}
$r = 5;
echo squarearea( $r );
?>
|
Javascript
<script>
function squarearea(r)
{
if (r < 0)
return -1;
var a = 4 * (Math.pow(r, 2) / 5);
return a;
}
var r = 5;
document.write( squarearea(r));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
20 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...