📌  相关文章
📜  可放入直角等腰三角形的最大 2×2 正方形数

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

在给定底的直角等腰三角形中可以容纳的大小为 2×2 单位的正方形的最大数量是多少(单位)。
正方形的一条边必须与三角形的底边平行。

例子:

Input  : 8
Output : 6
Please refer below diagram for explanation.

Input : 7
Output : 3

由于三角形是等腰三角形,给定的底也将等于高度。现在在对角线部分,我们总是需要三角形的高度和底边的 2 个单位的额外长度来容纳三角形。 (图像中三角形的 CF 和 AM 段。对任何正方形没有贡献的部分)。在base的剩余长度中,我们可以构造length / 2个正方形。由于每个正方形有 2 个单位,因此高度也是如此,无需再次计算。
因此,对于给定长度的每个级别,我们可以构造“(length-2)/2”正方形。这为我们提供了位于其上方的“(length-2)”的基础。继续这个过程以获得所有可用“长度-2”高度的平方数,我们可以计算平方。

while length > 2
    answer += (length - 2 )/2
    length = length - 2

对于更有效的方法,我们可以使用 AP n * ( n + 1 ) / 2 之和的公式,其中 n = length – 2

C++
// C++ program to count number of 2 x 2
// squares in a right isosceles triangle
#include
using namespace std;
 
int numberOfSquares(int base)
{
   // removing the extra part we would
   // always need
   base = (base - 2);
 
   // Since each square has base of
   // length of 2
   base = floor(base / 2);
 
   return base * (base + 1)/2;
}
 
// Driver code
int main()
{
   int base = 8;
   cout << numberOfSquares(base);
   return 0;
}
// This code is improved by heroichitesh.


Java
// Java program to count number of 2 x 2
// squares in a right isosceles triangle
 
class Squares
{
  public static  int numberOfSquares(int base)
   {
      // removing the extra part
      // we would always need
      base = (base - 2);
  
      // Since each square has
      // base of length of 2
      base = Math.floorDiv(base, 2);
  
      return base * (base + 1)/2;
   }
  
   // Driver code
   public static void main(String args[])
   {
       
      int base = 8;
      System.out.println(numberOfSquares(base));
   }
}
 
// This code is contributed by Anshika Goyal and improved by heroichitesh.


Python3
# Python3 program to count number
# of 2 x 2 squares in a right
# isosceles triangle
def numberOfSquares(base):
     
    # removing the extra part we would
    # always need
    base = (base - 2)
     
    # Since each square has base of
    # length of 2
    base = base // 2
     
    return base * (base + 1) / 2
     
# Driver code
base = 8
 
print(numberOfSquares(base))
 
# This code is contributed by Anant Agarwal and improved by heroichitesh.


C#
// C# program to count number of 2 x 2
// squares in a right isosceles triangle
using System;
 
class GFG {
     
    public static int numberOfSquares(int _base)
    {
         
        // removing the extra part
        // we would always need
        _base = (_base - 2);
     
        // Since each square has
        // base of length of 2
        _base = _base / 2;
     
        return _base * (_base + 1)/2;
    }
     
    // Driver code
    public static void Main()
    {
         
        int _base = 8;
        Console.WriteLine(numberOfSquares(_base));
    }
}
 
// This code is contributed by anuj_67.


PHP


Javascript


输出:

6

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