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