C# 根据给定的斜边和面积找到直角三角形的所有边 Find all sides of a right angled triangle from given hypotenuse and area

         给定直角三角形的斜边和面积,求出其底边和高,如果给定斜边和面积的任何三角形都不可能,则打印“不可能”。

示例: 

输入:斜边 = 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 
 
using System;
public class GFG{
 
 
// limit for float comparison 
     static double eps = (double) 1e-6; 
 
// Utility method to get area of right angle triangle, 
// given base and hypotenuse 
    static double getArea(double base1, double hypotenuse) { 
        double height = Math.Sqrt(hypotenuse * hypotenuse - base1 * base1); 
        return 0.5 * base1 * height; 
    } 
 
// Prints base and height of triangle using hypotenuse 
// and area information 
    static 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 = Math.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) { 
            Console.Write("Not possible"); 
            return; 
        } 
 
        double low = 0.0; 
        double high = sideForMaxArea; 
        double base1 = 0; 
 
        // binary search for base 
        while (Math.Abs(high - low) > eps) { 
            base1 = (low + high) / 2.0; 
            if (getArea(base1, hypotenuse) >= area) { 
                high = base1; 
            } else { 
                low = base1; 
            } 
        } 
 
        // get height by pythagorean rule 
        double height = Math.Sqrt(hsquare - base1 * base1); 
        Console.WriteLine(Math.Round(base1) + " " + Math.Round(height)); 
    } 
 
// Driver code to test above methods 
    static public void Main() { 
        int hypotenuse = 5; 
        int area = 6; 
 
        printRightAngleTriangle(hypotenuse, area); 
    } 

 
// This code is contributed by 29AjayKumar  

输出: 

3 4

时间复杂度: O(log(n)),因为使用内置 sqrt 函数

辅助空间: O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

csdn_aspnet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值