×

Centered Square Numbers in Java

In this tutorial, we will understand how to check the number is a centered square number. It is one of the prevalent interview questions of IT companies. Firstly, we will understand the meaning of centered square numbers later we will create a java program for the same.

Centered Square Numbers

Centered Square numbers are the figurate numbers

that are recursively described as:

Q(num) = Q(num - 1) + 4 x (num - 1), where num >= 1 and Q(0) = 1  

Example:

For num = 1ry of Java

Q(1) = Q(1 - 1) + 4 x (1 - 1) => Q(1) = Q(0) + 4 x 0 = 1 + 0 = 1

For num = 2

Q(2) = Q(2 - 1) + 4 x (2 - 1) => Q(2) = Q(1) + 4 x 1 = 1 + 4 = 5

For num = 3

Q(3) = Q(3 - 1) + 4 x (3 - 1) => Q(3) = Q(2) + 4 x 2 = 5 + 8 = 13

For num = 4

Q(4) = Q(4 - 1) + 4 x (4 - 1) => Q(4) = Q(3) + 4 x 3 = 13 + 12 = 25

For num = 5

Q(5) = Q(5 - 1) + 4 x (5 - 1) => Q(5) = Q(4) + 4 x 4 = 25 + 16 = 41

Implementation

Approach 1: Recursive

Let us now see a recursive java program to find the first fifteen centered square numbers.

public class CenteredSquareNumber   
{  
public int detectCenteredSqureNum(int n)   
{  
// dealing with the base case  
if(n == 1)  
{  
    return n;  
}  
// calculation of the central square number recursively   
return detectCenteredSqureNum(n - 1) + 4 * (n - 1);  
}  
// beginning of the Main method  
public static void main(String[] argvs)   
{  
// creation of an object of the class named CenteredSquareNumber  
CenteredSquareNumber obj = new CenteredSquareNumber();  
// calculation of 15 centered square numbers  from the beginning
int num = 15;  
System.out.println("The first " + num + " Centered Square Number are: \n");  
for(int j = 1; j <= 15; j++)  
{  
int res = obj.detectCenteredSqureNum(j);  
System.out.print(res + " ");  
}  
}  
}  

Output:

Centered Square Numbers in Java

Explanation: The above program has space complexity = O(1).

The time complexity of the program O(t), where t is the tth position of the central square number that is to be found.

Approach 2: Iterative

The above program is optimized to reduce the complexities. Here, an array is used to store the result.

public class CenteredSquareNumber2   
{  
// Main method  
public static void main(String[] argvs)   
{  
// calculating the initial 15 centered square numbers  
int n = 15;  
// creation of an array to store the calculated centered square number  
int res[] = new int[n + 1];  
System.out.println("The first " + n + " Centered Square Number are: \n");  
for(int j = 1; j <= 15; j++)  
{  
// dealing with the base case  
if(j == 1)  
{  
    res[j] = 1;  
}  
else  
{  
    res[j] = res[j - 1] + 4 * (j - 1);  
}  
// displaying the result  
System.out.print(res[j] + " ");  
}  
}  
}  

Output:

Centered Square Numbers in Java

Explanation: The space complexity of the above program =  O(n). here, n is the total number of central squared numbers to be calculated. and the time complexity = O(1).

Approach 3:

This is another optimized approach.

public class CenteredSquareNumber3  
{  
// beginning of the main method
public static void main(String[] argvs)   
{  
// calculating the first 15 centered square numbers  
int n = 15;  
// A variable to store just the last computed centered square number  
int lastCenSqrdNum = 0;  
System.out.println("The first " + n + " Centered Square Number are: \n");  
for(int j = 1; j <= 15; j++)  
{  
// dealing with the base case  
if(j == 1)  
{  
    lastCenSqrdNum = 1;  
}  
else  
{  
    lastCenSqrdNum = lastCenSqrdNum + 4 * (j - 1);  
}  
// displaying the result  
System.out.print(lastCenSqrdNum + " ");  
}  
}  
}  

Output:

Centered Square Numbers in Java

Explanation: The time complexity here = O(1). The space complexity also is O(1) as no arrays have been taken into account to store the resultant.

Approach 4: Mathematical formula

Q(num) = num2 + (num - 1)2, where num>= 1

Example:

For num = 1

Q(1) = 12 + (1 - 1)2 => Q(1) = 1 + 02 = 1 + 0 = 1

For num = 2

Q(2) = 22 + (2 - 1)2 => Q(2) = 4 + 12 = 4 + 1 = 5

public class CenteredSquareNumber4  
{  
// Beginning of the Main method  
public static void main(String[] argvs)   
{  
// calculating the first 15 centered square numbers  
int n = 15;  
System.out.println("The first " + n + " Centered Square Number are: \n");  
for(int j = 1; j <= 15; j++)  
{  
int res = (j * j) + ((j - 1) * (j - 1));  
// displaying the result  
System.out.print(res + " ");  
}  
}  
}  

Output:

Centered Square Numbers in Java

Explanation: The time complexity = O(1) .The space complexity = O(1).


Related Topics

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Intersection Point of two linked list in Java

In this article, you will be very well acknowledged about how to achieve the intersection point of two linked list in Java. There are several approaches to obtain. Surely each...

8 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Can Abstract Classes have Static Methods in Java

Abstract Class An abstract class in Java is one that explicitly uses the keyword "abstract" in its declaration. There are options for both non-abstract and abstract techniques (method with the body)....

4 minutes read.

Java Math random() Method

The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with...

1 minute read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Series Program in Java

Series Program in Java The series program in Java is written to print the mathematical series such as the Fibonacci series, Pell series, etc. A few of the renowned series are...

12 minutes read.

Java Integer valueOf() method

The valueOf() method of Java Integer class returns an Integer object holding the specified int value. The second method returns an Integer object holding the specified String value. The third syntax returns...

2 minutes read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Java Integer toString() method

The toString() method of Java Integer class returns a String object which represents this Integer’s value. The second syntax returns a String object which represents the specified integer. The third syntax returns...

2 minutes read.