📜  拼图 |寻找棋盘中方格数的程序

📅  最后修改于: 2021-10-23 07:42:04             🧑  作者: 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


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


Javascript


输出:

Count of squares is 30

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