![]() |
VOOZH | about |
Given hypotenuse and area of a right angle triangle, get its base and height and if any triangle with given hypotenuse and area is not possible, print not possible.
Examples:
Input : hypotenuse = 5, area = 6 Output : base = 3, height = 4 Input : hypotenuse = 5, area = 7 Output : No triangle possible with above specification.
We can use a property of right angle triangle for solving this problem, which can be stated as follows,
A right angle triangle with fixed hypotenuse attains maximum area, when it is isosceles i.e. both height and base becomes equal so if hypotenuse if H, then by pythagorean theorem, Base2 + Height2 = H2 For maximum area both base and height should be equal, b2 + b2 = H2 b = sqrt(H2/2) Above is the length of base at which triangle attains maximum area, given area must be less than this maximum area, otherwise no such triangle will possible.
Now if given area is less than this maximum area, we can do a binary search for length of base, as increasing base will increases area, it is a monotonically increasing function where binary search can be applied easily.
In below code, a method is written for getting area of right angle triangle, recall that for right angle triangle area is ½*base*height and height can be calculated from base and hypotenuse using pythagorean theorem.
Below is the implementation of above approach:
Output:
3 4
Time complexity: O(log(n)) because using inbuilt sqrt function
Auxiliary Space: O(1)
One more solution is discussed in below post.
Check if right angles possible from given area and hypotenuse