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

📅  最后修改于: 2021-04-24 17:15:25             🧑  作者: Mango

可以适合给定基数的直角等腰三角形的大小为2×2单位的最大平方数(以单位为单位)。
正方形的一侧必须与三角形的底边平行。

例子:

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

Input : 7
Output : 3

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

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

为了更有效的方法,我们可以使用AP n *(n + 1)/ 2的和的公式,其中n =长度– 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