📌  相关文章
📜  直角等腰三角形可以容纳的最大正方形数

📅  最后修改于: 2021-10-23 08:29:23             🧑  作者: Mango

给定一个等腰(至少有两条边相等的三角形)直角三角形,底边为 b,我们需要找到边 m 的最大正方形数,它可以拟合到给定的三角形中。
例子:

Input : b = 6, m = 2
Output : 3

Input : b = 4, m = 1
Output : 6

让我们考虑一个直角三角形 XYZ,其中 YZ 是三角形的底。假设底的长度是b。如果我们考虑第一个正方形与顶点 Y 的位置,我们将在底边有 (b / m-1) 个正方形,我们将留下另一个底长为 (b – m) 的等腰直角三角形。
插图 :

设 f(b, m) = 可拟合为底长为 b 的三角形的正方形数。
然后f(b, m) = (b / m – 1) + f(b – m, m)
我们可以使用上述递归并使用记忆来计算 f(b)。稍后我们可以在 O(1) 时间内回答每个查询。如果 (b < 2 * m) f(b, m) = 0,我们可以在基本情况下分别对偶数和奇数进行计算。
给定的递归可以解决为:
f(b, m) = b / m – 1 + f(b – m, m) = b / m – 1 + (b – m) / m – 1 + f(b – 2m, m)
f(b, m) = b / m – 1 + b / m – 2 + f(b – 3m, m) +…+ f(b – (b / m)m, m)
f(b) = b / m – 1 + b / m – 2 + b / m – 3 +…..+ 1 + 0
有条件,如果(b < 2 * m) f(b, m) = 0
f(b) = 第一个 (b / m – 1) 自然数之和
= (b / m – 1) * (b / m) / 2
该公式可用于将时间复杂度降低到 O(1)。

C++
// CPP program for finding maximum squares
// that can fit in right angle isosceles
// triangle
#include
using namespace std;
 
// function for finding max squares
int maxSquare(int b, int m)
{
    // return in O(1) with derived
    // formula
    return (b / m - 1) * (b / m) / 2;
}
 
// driver program
int main()
{
    int b = 10, m = 2;
    cout << maxSquare (b,m);
    return 0;
}


Java
// Java program for finding maximum squares
// that can fit in right angle isosceles
// triangle
public class GFG
{    
    // function for finding max squares
    static int maxSquare(int b, int m)
    {
        // return in O(1) with derived
        // formula
        return (b / m - 1) * (b / m) / 2;
    }
      
    // driver program
    public static void main(String args[])
    {
        int b = 10, m = 2;
        System.out.println(maxSquare (b,m));
    }
}
 
// This code is contribute by Sumit Ghosh


Python3
# Python3 program for
# finding maximum squares
# that can fit in
# right angle isosceles
# triangle
 
# function for finding max squares
def maxSquare(b, m):
  
    # return in O(1) with derived
    # formula
    return (b / m - 1) * (b / m) / 2
  
 
# driver program
b = 10
m = 2
print(int(maxSquare (b,m)))
 
# This code is contributed by
# Smitha Dinesh Semwal


C#
// C# program for finding maximum squares
// that can fit in right angle isosceles
// triangle
using System;
 
public class GFG
{
    // function for finding max squares
    static int maxSquare(int b, int m)
    {
        // return in O(1) with derived
        // formula
        return (b / m - 1) * (b / m) / 2;
    }
     
    // driver program
    public static void Main()
    {
        int b = 10, m = 2;
        Console.WriteLine(maxSquare (b, m));
    }
}
 
// This code is contribute by vt_m


PHP


Javascript


输出:

10

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程