给定直角三角形的斜边和面积,求出其底边和高,如果给定斜边和面积的任何三角形都不可能,则打印“不可能”。
示例:
输入:斜边 = 5,面积 = 6
输出:底边 = 3,高 = 4
输入:斜边 = 5,面积 = 7
输出:根据上述规范,不可能形成三角形。
我们可以利用直角三角形的性质来解决这个问题,具体如下:
具有固定斜边的直角三角形
在为等腰三角形时面积最大,即高
和底边相等,因此如果斜边为 H,则
根据勾股定理,
底边² + 高² = H²
要获得最大面积,底边和高应该相等,
b² + b² = H²
b = sqrt(H²/2)
以上是三角形获得最大面积时的底边长度
,给定面积必须小于此最大
面积,否则不可能出现这样的三角形。
现在,如果给定的面积小于此最大面积,我们可以对底边的长度进行二分查找,因为增加底边将增加面积,这是一个单调递增函数,可以轻松应用二分查找。
在下面的代码中,编写了一种获取直角三角形面积的方法,回想一下,对于直角三角形,面积是 ½*底边*高,可以使用勾股定理根据底边和斜边计算出高。
以下是上述方法的实现:
// C++ program to get right angle triangle, given
// hypotenuse and area of triangle
#include <bits/stdc++.h>
using namespace std;
// limit for float comparison
#define eps 1e-6
// Utility method to get area of right angle triangle,
// given base and hypotenuse
double getArea(double base, double hypotenuse)
{
double height = sqrt(hypotenuse*hypotenuse - base*base);
return 0.5 * base * height;
}
// Prints base and height of triangle using hypotenuse
// and area information
void printRightAngleTriangle(int hypotenuse, int area)
{
int hsquare = hypotenuse * hypotenuse;
// maximum area will be obtained when base and height
// are equal (= sqrt(h*h/2))
double sideForMaxArea = sqrt(hsquare / 2.0);
double maxArea = getArea(sideForMaxArea, hypotenuse);
// if given area itself is larger than maxArea then no
// solution is possible
if (area > maxArea)
{
cout << "Not possiblen";
return;
}
double low = 0.0;
double high = sideForMaxArea;
double base;
// binary search for base
while (abs(high - low) > eps)
{
base = (low + high) / 2.0;
if (getArea(base, hypotenuse) >= area)
high = base;
else
low = base;
}
// get height by pythagorean rule
double height = sqrt(hsquare - base*base);
cout << base << " " << height << endl;
}
// Driver code to test above methods
int main()
{
int hypotenuse = 5;
int area = 6;
printRightAngleTriangle(hypotenuse, area);
return 0;
}
输出:
3 4
时间复杂度: O(log(n)),因为使用内置 sqrt 函数
辅助空间: O(1)