×

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

Java Integer reverseByte() method

The reverseByte() method of Java Integer class returns the value obtained by reversing the order of the bytes in the 2’s complement binary representation. Syntax public static int reverseByte (int i) Parameters The parameter...

1 minute read.

Java Programming certification

The most common technology utilized in the creation of applications is Java. People and businesses like it because it turns original ideas into useful software solutions. A Java programming certification can...

6 minutes read.

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.

Isomorphic String in Java

In this tutorial, we will understand what is meant by isomorphic String in java. We will also see a Java program to find out if the string is isomorphic or...

4 minutes read.

Java Math atan() Method

The atan() method of Math class computes the trigonometric Arc Tangent (inverse of tangent ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double atan(double a) Parameters: The...

2 minutes read.

TreeSet in Java

Java TreeSet with Example Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not...

8 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Magnanimous Number in java

Magnanimous Number When the left and right halves of a majestic number are combined, the result is invariably a prime number, which must have at least two digits. The number's left...

3 minutes read.

Java Class Syntax

A class is a fundamental building piece in object-oriented programming. It can be characterised as a template that outlines the information and actions connected to the creation of a class....

3 minutes read.

Java Integer numberOfLeadingZeros() method

The numberOfLeadingZeros()  method of Java Integer class returns the total number of zero bits preceding the highest-order one-bit in the 2’s complement binary representation of the specified int value.  Syntax public static...

1 minute read.

Java Arrays

An array is an object that stores a collection of values. An array can store two types of collection data: objects and primitives. An array is a collection of values which...

2 minutes read.

Java Vs C++

Java Vs C++ Java and C++ both are Object Oriented Programming languages. Both languages are popular for competitive programming. C++ is used by many coders who have just started learning programming...

4 minutes read.

Bounded buffer problem in Java

The Bounded buffer Problem can also be called a Producer consumer problem. The problem covers two processes—the producer and the consumer—that share a single, fixed-size buffer that serves as a...

4 minutes read.

Web Service Response Time Calculation in Java

Administration response time or reaction time is the typical measure of time it takes for a solicitation to be handled by a PC framework, like your organization switch. In the...

4 minutes read.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.