📜  拼图|在棋盘上找到方块数的程序

📅  最后修改于: 2021-04-26 10:32:38             🧑  作者: Mango

难题:为您提供了一个棋盘,并要求您在其中找到正方形的数量。棋盘是其中具有8 x 8网格的棋盘,如下所示。

解决方案仔细观察棋盘,我们可以看到除了1 x 1正方形以外,还可以有2 x 2、3 x 3、4 x 4、5 x 5、6 x 6、7 x 7的组合。还有8 x 8平方要获得平方的总数,我们需要找到所有形成的平方。

1 x 1: 8 * 8 = 64 squares.
2 x 2: 7 * 7 = 49 squares.
3 x 3: 6 * 6 = 36 squares.
4 x 4: 5 * 5 = 25 squares.
5 x 5: 4 * 4 = 16 squares.
6 x 6: 3 * 3 = 9 squares.
7 x 7: 2 * 2 = 4 squares.
8 x 8: 1 * 1 = 1 square.

因此,我们在棋盘上总共有= 64 + 49 + 36 + 25 + 16 + 9 + 4 + 1 = 204个正方形。

一般流程

给定一个nxn的网格,在其中计算正方形。

例子 :

Input: n = 2
Output: 5 (4 squares of 1 unit + 1 square of 2 units)

Input: n = 3
Output: 14 (9 squares of 1 unit + 4 square of 2 units 
                                + 1 square of 1 unit)

对于大小为n * n的网格,形成的正方形总数为:

1^2 + 2^2 + 3^2 + ... + n^2 = n(n+1)(2n+1) / 6 

下面是上述公式的实现。由于n *(n + 1)*(2n + 1)的值可能会导致较大的n值溢出,因此以下是该程序中使用的一些有趣技巧。

  1. long int用于返回。
  2. 首先评估n *(n +1)/ 2,因为值n *(n + 1)始终是2的倍数。

请注意,仍然可能发生溢出,但是上述技巧只是减少了溢出的机会。

C
#include 
using namespace std;
  
// Function to return count of squares;
long int countSquares(int n)
{
    // A better way to write n*(n+1)*(2n+1)/6
    return (n * (n + 1) / 2) * (2*n + 1) / 3;
}
  
int main()
{
  int n = 4;
  cout << "Count of squares is " << countSquares(n);
  return 0;
}


Java
// Java  find number of squares in a 
// chessboard
  
  
class GFG 
{
    // Function to return count of squares;
    static int countSquares(int n)
    {
        // A better way to write n*(n+1)*(2n+1)/6
        return (n * (n + 1) / 2) * (2 * n + 1) / 3;
    }
      
    // Driver code
    public static void main (String[] args)
    {
        int n = 3;
        System.out.println("Count of squares is "
                           +countSquares(n));
    }
}
  
// This code is contributed by Anant Agarwal.


Python3
# python code to find number 
# of squares in a chessboard
  
# Function to return count
# of squares;
def countSquares(n):
      
    # better way to write
    # n*(n+1)*(2n+1)/6
    return ((n * (n + 1) / 2) 
           * (2 * n + 1) / 3)
      
# Driver code
n = 4
print("Count of squares is ",
              countSquares(n))
  
# This code is contributed by sam007.


C#
// C# find number of squares in a 
// chessboard
using System;
  
public class GFG {
      
    static int countSquares(int n)
    {
        // A better way to write 
        // n*(n+1)*(2n+1)/6
        return (n * (n + 1) / 2) 
                * (2 * n + 1) / 3;
    }
      
    // Driver code
    public static void Main ()
    {
        int n = 4;
        Console.WriteLine("Count of"
                     + "squares is "
                 + countSquares(n));
    }
}
  
// This code is contributed by Sam007.


PHP


输出 :

Count of squares is 30