Program to find the Radius of the incircle of the triangle
Last Updated :
20 Aug, 2022
Given a circle which is the incircle of a triangle whose sides are a, b< and c, the task is to find the radius of this incircle.
Examples:
Input: a = 2, b = 2, c = 3
Output: 0.566947
Input: a = 3, b = 4, c = 5
Output: 1
Approach:
Radius of the incircle = area of the triangle / half of perimeter of the triangle
where:
Area of the triangle = √(p*(p-a)*(p-b)*(p-c)
perimeter of the triangle = (a + b + c)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float findRadiusOfIncircle( float a, float b, float c)
{
if (a < 0 || b < 0 || c < 0)
return -1;
float p = (a + b + c) / 2;
float area = sqrt (p * (p - a) * (p - b) * (p - c));
float radius = area / p;
return radius;
}
int main()
{
float a = 2, b = 2, c = 3;
cout << findRadiusOfIncircle(a, b, c)
<< endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
static float findRadiusOfIncircle( float a, float b, float c)
{
if (a < 0 || b < 0 || c < 0 )
return - 1 ;
float p = (a + b + c) / 2 ;
float area = ( float )Math.sqrt(p * (p - a) * (p - b) * (p - c));
float radius = area / p;
return radius;
}
public static void main (String[] args) {
float a = 2 , b = 2 , c = 3 ;
System.out.println( findRadiusOfIncircle(a, b, c));
}
}
|
Python3
from math import *
def findRadiusOfIncircle(a, b, c) :
if (a < 0 or b < 0 or c < 0 ) :
return - 1
p = (a + b + c) / 2
area = sqrt(p * (p - a) *
(p - b) * (p - c))
radius = area / p
return radius
if __name__ = = "__main__" :
a, b, c = 2 , 2 , 3
print ( round (findRadiusOfIncircle(a, b, c), 6 ))
|
C#
using System;
class GFG
{
public static float findRadiusOfIncircle( float a,
float b,
float c)
{
if (a < 0 || b < 0 || c < 0)
return -1;
float p = (a + b + c) / 2;
float area = ( float )Math.Sqrt(p * (p - a) *
(p - b) * (p - c));
float radius = area / p;
return ( float )(radius);
}
public static void Main()
{
float a = 2, b = 2, c = 3;
Console.WriteLine(findRadiusOfIncircle(a, b, c));
}
}
|
PHP
<?php
function findRadiusOfIncircle( $a , $b , $c )
{
if ( $a < 0 || $b < 0 || $c < 0)
return -1;
$p = ( $a + $b + $c ) / 2;
$area = sqrt( $p * ( $p - $a ) *
( $p - $b ) * ( $p - $c ));
$radius = $area / $p ;
return $radius ;
}
$a = 2; $b = 2; $c = 3;
echo findRadiusOfIncircle( $a , $b , $c ) . "\n" ;
|
Javascript
<script>
function findRadiusOfIncircle(a , b , c)
{
if (a < 0 || b < 0 || c < 0)
return -1;
var p = (a + b + c) / 2;
var area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
var radius = area / p;
return radius;
}
var a = 2, b = 2, c = 3;
document.write( findRadiusOfIncircle(a, b, c).toFixed(6));
</script>
|
Time complexity: O(log(n)) because using inbuilt sqrt function
Auxiliary Space: O(1), since no extra space has been taken.
Share your thoughts in the comments
Please Login to comment...