Number of cells in the Nth order figure
Last Updated :
11 Jul, 2022
Given an integer N, the task is to find the number of cells in Nth order figure of the given type:
Examples:
Input: N = 2
Output: 5
Input: N = 3
Output: 13
Approach: It can be observed that for the values of N = 1, 2, 3, … a series will be formed as 1, 5, 13, 25, 41, 61, 85, 113, 145, 181, … whose Nth term will be N2 + (N – 1)2.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int cntCells( int n)
{
int cells = pow (n, 2) + pow (n - 1, 2);
return cells;
}
int main()
{
int n = 3;
cout << cntCells(n);
return 0;
}
|
Java
class GFG
{
static int cntCells( int n)
{
int cells = ( int )Math.pow(n, 2 ) +
( int )Math.pow(n - 1 , 2 );
return cells;
}
public static void main(String[] args)
{
int n = 3 ;
System.out.println(cntCells(n));
}
}
|
Python3
def cntCells(n) :
cells = pow (n, 2 ) + pow (n - 1 , 2 );
return cells;
if __name__ = = "__main__" :
n = 3 ;
print (cntCells(n));
|
C#
using System;
class GFG
{
static int cntCells( int n)
{
int cells = ( int )Math.Pow(n, 2) +
( int )Math.Pow(n - 1, 2);
return cells;
}
public static void Main(String[] args)
{
int n = 3;
Console.WriteLine(cntCells(n));
}
}
|
Javascript
<script>
function cntCells(n)
{
var cells = Math.pow(n, 2) + Math.pow(n - 1, 2);
return cells;
}
var n = 3;
document.write(cntCells(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1), as no extra space is required
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...