📜  计数刻在尺寸N的正方形上的尺寸K的平方

📅  最后修改于: 2021-04-29 10:09:12             🧑  作者: Mango

给定两个整数NK ,任务是找到大小为N的正方形内接的大小为K的正方形数。

例子:

方法:解决该问题的关键观察是,大小为N的正方形的平方总数为(N *(N + 1)*(2 * N +1))/ 6 。因此,大小为N的正方形可能得到的大小为K的正方形总数为:

下面是上述方法的实现:

C++
// C++ implementation of the
// above approach
 
#include 
using namespace std;
 
// Function to calculate the number
// of squares of size K in a square
// of size N
int No_of_squares(int N, int K)
{
    // Stores the number of squares
    int no_of_squares = 0;
 
    no_of_squares
        = (N - K + 1) * (N - K + 1);
 
    return no_of_squares;
}
 
// Driver Code
int main()
{
    // Size of the
    // bigger square
    int N = 5;
 
    // Size of
    // smaller square
    int K = 3;
    cout << No_of_squares(N, K);
    return 0;
}


Java
// Java implementation of the
// above approach
import java.util.*;
class GFG{
 
// Function to calculate the
// number of squares of size
// K in a square of size N
static int No_of_squares(int N,
                         int K)
{
  // Stores the number
  // of squares
  int no_of_squares = 0;
 
  no_of_squares = (N - K + 1) *
                  (N - K + 1);
 
  return no_of_squares;
}
 
// Driver Code
public static void main(String[] args)
{
  // Size of the
  // bigger square
  int N = 5;
 
  // Size of
  // smaller square
  int K = 3;
  System.out.print(No_of_squares(N, K));
}
}
 
// This code is contributed by Princi Singh


Python3
# Python3 implementation of the
# above approach
 
# Function to calculate the
# number of squares of size
# K in a square of size N
def No_of_squares(N, K):
   
    # Stores the number
    # of squares
    no_of_squares = 0;
    no_of_squares = (N - K + 1) * (N - K + 1);
    return no_of_squares;
 
# Driver Code
if __name__ == '__main__':
   
    # Size of the
    # bigger square
    N = 5;
 
    # Size of
    # smaller square
    K = 3;
    print(No_of_squares(N, K));
 
# This code is contributed by 29AjayKumar


C#
// C# implementation of the
// above approach
using System;
 
class GFG{
 
// Function to calculate the
// number of squares of size
// K in a square of size N
static int No_of_squares(int N, int K)
{
     
    // Stores the number
    // of squares
    int no_of_squares = 0;
     
    no_of_squares = (N - K + 1) *
                    (N - K + 1);
     
    return no_of_squares;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Size of the
    // bigger square
    int N = 5;
     
    // Size of
    // smaller square
    int K = 3;
     
    Console.Write(No_of_squares(N, K));
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:
9

时间复杂度: O(1)
辅助空间: O(1)