📌  相关文章
📜  无需抬起铅笔即可绘制的平方数

📅  最后修改于: 2021-04-23 16:24:02             🧑  作者: Mango

给定一个整数N ,任务是查找不举铅笔就可以绘制的面1的平方数,该点从N * N网格的一个角开始,并且从不访问边缘两次。

方法:可以观察到,对于N = 1,2,3,…的值,一个序列将形成为1,2,5,10,17,26,37,50,…,N项是( N 2 –(2 * N)+ 2)
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the count of
// squares that can be formed
int countSquares(int n)
{
    return (pow(n, 2) - (2 * n) + 2);
}
 
// Driver code
int main()
{
    int n = 2;
 
    cout << countSquares(n);
 
    return 0;
}


Java
// Java implementation of the approach
class GFG
{
 
// Function to return the count of
// squares that can be formed
static int countSquares(int n)
{
    return (int) (Math.pow(n, 2) - (2 * n) + 2);
}
 
// Driver code
public static void main(String []args)
{
    int n = 2;
    System.out.println(countSquares(n));
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 implementation of the approach
 
# Function to return the count of
# squares that can be formed
def countSquares(n) :
 
    return (pow(n, 2) - (2 * n) + 2);
 
# Driver code
if __name__ == "__main__" :
 
    n = 2;
 
    print(countSquares(n));
 
# This code is contributed by AnkitRai01


C#
// C# implementation of the approach
using System;
                     
class GFG
{
 
    // Function to return the count of
    // squares that can be formed
    static int countSquares(int n)
    {
        return (int) (Math.Pow(n, 2) - (2 * n) + 2);
    }
     
    // Driver code
    public static void Main(String []args)
    {
        int n = 2;
        Console.WriteLine(countSquares(n));
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
2

时间复杂度: O(1)