📜  在棋s中计算具有奇数边长的正方形

📅  最后修改于: 2021-05-06 07:23:47             🧑  作者: Mango

给定N * N的棋盘,任务是计算边长为奇数的方格数。

例子:

方法:对于从1N的所有奇数,然后计算可以形成具有该奇数边的平方数。对于i面,正方形的计数等于(N – I + 1)2。进一步加上所有这样的平方数。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the count
// of odd length squares possible
int count_square(int n)
{
  
    // To store the required count
    int count = 0;
  
    // For all odd values of i
    for (int i = 1; i <= n; i = i + 2) {
  
        // Add the count of possible
        // squares of length i
        int k = n - i + 1;
        count += (k * k);
    }
  
    // Return the required count
    return count;
}
  
// Driver code
int main()
{
    int N = 8;
  
    cout << count_square(N);
  
    return 0;
}


Java
// Java implementation of the approach
class GFG {
  
    // Function to return the count
    // of odd length squares possible
    static int count_square(int n)
    {
  
        // To store the required count
        int count = 0;
  
        // For all odd values of i
        for (int i = 1; i <= n; i = i + 2) {
  
            // Add the count of possible
            // squares of length i
            int k = n - i + 1;
            count += (k * k);
        }
  
        // Return the required count
        return count;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int N = 8;
  
        System.out.println(count_square(N));
    }
}
  
// This code is contributed by Rajput-Ji


Python3
# Python implementation of the approach
  
# Function to return the count
# of odd length squares possible
def count_square(n):
  
    # To store the required count
    count = 0;
  
    # For all odd values of i
    for i in range(1, n + 1, 2):
  
        # Add the count of possible
        # squares of length i
        k = n - i + 1;
        count += (k * k);
  
    # Return the required count
    return count;
  
# Driver code
N = 8;
print(count_square(N));
  
# This code has been contributed by 29AjayKumar


C#
// C# implementation of the approach
using System;
  
class GFG {
  
    // Function to return the count
    // of odd length squares possible
    static int count_square(int n)
    {
  
        // To store the required count
        int count = 0;
  
        // For all odd values of i
        for (int i = 1; i <= n; i = i + 2) {
  
            // Add the count of possible
            // squares of length i
            int k = n - i + 1;
            count += (k * k);
        }
  
        // Return the required count
        return count;
    }
  
    // Driver code
    public static void Main()
    {
        int N = 8;
  
        Console.WriteLine(count_square(N));
    }
}
  
// This code is contributed by Code_Mech.


PHP


输出:
120