×

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 mentioned below.

  • Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, …
  • Pell series: 0, 1, 2, 5, 12, 29, 70, 169, 408, 985, 2378, 5741, 13860, 33461, …
  • Catalan number series: 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, …

Note: We have started the Catalan series with the 0th term.

  • Triangular number series: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, …
  • Square number series: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, …
  • Cube number series: 1, 8, 27, 64, 125, 216, 343, 512, 729, 1000, 1331, 1728, …

We will discuss each of the series mentioned above. Let’s begin with the Fibonacci series.

Fibonacci Series

Fibonacci series is a series whose next term is the summation of the last two terms. The first two terms of the series are 0 and 1. Thus, the third term is the addition of the first and the second term, i.e., 0 + 1 = 1, the fourth term becomes 1 + 1 = 2, and the fifth term becomes 1 + 2 = 3. Similarly, we can easily find the rest of the terms.

Pell Series

Pell series is the series whose next term is the addition of the second last term and the twice of the last term. The first two terms of the series are 0 and 1, respectively. Hence, the third term becomes summation of the first term and the twice of the second term, i.e., 0 + 1 * 2= 2, the fourth term is 1 + 2 * 2= 5, and the fifth term is 2 + 5 * 2= 12, and so on. Thus, if we have to find the nth term (Tn), we can represent it as:

Tn = Tn - 2 + (Tn – 1 * 2), where n > 2.

The following Java code uses the above mathematical relation to print the terms of the Pell series.

Using Java for Loop

Filename: PellSeriesIterative.java

public class PellSeriesIterative
{
public static void main(String argvs[])
{
               int t1 = 0, t2 = 1; // the first two terms
               // Defines the number of terms upto which we are printing the Pell series
               int noOfTerms = 15;
               System.out.print("The first " + noOfTerms + " terms of Pell series are: \n");
               for(int i = 1; i <= noOfTerms; i++)
               {
                               if( i == 1) // printing the first term
                               {
                                              System.out.print(t1 + " ");
                               }
                               else if(i == 2) // printing the second term
                               {
                                              System.out.print(t2 + " ");
                               }
                               else // printing the rest of the term
                               {
                                              int t3 = t1 + t2 * 2;
                                              System.out.print(t3 + " ");
                                              // preparing for the next iteration
                                              // updating the t1 and t2 variable.
                                              t1 = t2;
                                              t2 = t3;
                               }
               }
}
} 

Output:

 The first 15 terms of Pell series are:
0 1 2 5 12 29 70 169 408 985 2378 5741 13860 33461 80782 

Explanation: In the above program, the variables t1 and t2 are representing the first two terms of the Pell series. The noOfTerms variable is controlling up to which term the Java for-loop is displaying the Pell series. From the 3rd iteration, we are calculating the next term of the Pell series using the mathematical relation defined above the code.

Using Recursion

Filename: PellSeriesRecursive.java

public class PellSeriesRecursive
{
// Method for finding terms of the Pell Series
public static int pellTerms(int n)
{
               if( n <= 1 ) // base case
               {
                               return n;
               }
               // recursively finding the terms
               return (2 * pellTerms(n - 1)) + pellTerms(n - 2);
}
public static void main(String argvs[])
{
               // Defines the number of terms up to which we are printing the Pell series
               int noOfTerms = 15;
               System.out.print("The first " + noOfTerms + " terms of Pell series are: \n");
                for(int i = 0; i < noOfTerms; i++)
                {
                               // invoking the method and storing the outcome
                              int term = pellTerms(i);
                              // displaying the terms of the Pell series
                              System.out.print(term + " ");
                }
}
} 

Output:

 The first 15 terms of Pell series are:
0 1 2 5 12 29 70 169 408 985 2378 5741 13860 33461 80782 

Explanation: In the code, the iteration of the Java for-loop depends on the value of the variable noOfTerms. In our case, the loop is iterating 15 times (0 to 14). When the value of the loop variable i is 0, we display the first term of the Pell series. For i = 1, we display the second term of the series, and so on. In each iteration, we are invoking the method pellTerms() and storing the result. The method pellTerms() is finding the (i + 1)th term, recursively, using the mathematical relation defined above.

Catalan Number Series

Catalan number series is a series of natural numbers that are used in various interesting problems where counting is required. Using Combination, the series is represented as:

   2nCn, where n >= 0. On further simplification we get,

     , where n >= 0    where n >= 0.

Thus, for n = 0, we get:

 =  = =  = 1

For n = 1, we get:

 =  = =  = 1

For n = 2, we get:

 =  = =  = 2

For n = 3, we get:

 =  = =  = 5

Similarly, we can calculate for any value of n.

The following Java program uses the Java for-loop to display the Catalan number series with the help of the above mathematical formula.

Using Java for-loop

Filename: CatalanSeriersIterative.java

public class CatalanSeriesIterative
{
public static void main(String argvs[])
{
               // Defines the number of terms upto which we are printing the Catalan series
               int noOfTerms = 15;
               System.out.print("The first " + noOfTerms + " terms of Catalan series are: \n");
               // We start from 0th term
               for(int i = 0; i < noOfTerms; i++)
               {
                               long term = 1; // initialized by 1 for calculating terms of the series
                               // The following for loops is calculating 
                               for(int j = i + 2; j <= 2 * i; j++)
                               {
                                   //  = (n + 2) * (n + 3) * (n +4) * … * 2n           
                                   term = term * j;
                               }
                               for(int j = 2; j <= i; j++)
                               {
                                  // whatever the result we get in the above loop
                                  // must be divided by the n! = (1 * 2 * 3 * … * n).  
                                  term = term / j;
                               }
                               // displaying the terms
                               System.out.print(term + " ");
               }
}
} 

Output:

 The first 15 terms of the Catalan series are:
1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 

Explanation: Similar to the above examples, this time also, the variable noOfTerms is controlling the number of terms being displayed on the console. Notice, in the loop, the variable term is of type long, which is used for displaying the terms of the series. Instead of the variable of type long, we cannot use a variable of type integer because the numbers are of bigger size when we display the higher terms of the Catalan series. Instead of using a long variable for displaying terms, still, we have to take care of the overflow, i.e., the number can be bigger than the capacity of a long variable. For example, if we have calculated 2n! factorial separately, then for n = 12, we have to calculate 24! which is equal to 620448401733239439360000.  Now, this big number is impossible to store in a long variable. Therefore, we have used two for loops of calculating the terms where we are doing the multiplication and division process side by side so that the resultant number does fit in a long variable.

Using Recursion

Before writing the code, let us define the recursive formula for calculating the numbers of the Catalan series.

T(0) = 1 [Base case]

And,

T(n) = T(i)  T(n - i - 1), for n >= 1

Thus,

T(1) = T(i)  T(1 - i - 1) = T(0)  T(1 – 0 - 1) = T(0)  T(0) = 1  1 = 1

T(2) = T(i)  T(2 - i - 1) = T(0)  T(2 - 0 - 1) + T(1)  T( 2 - 1 - 1)

   = T(0)  T(1) + T(1)  T(0) = 1  1 + 1  1 = 1 + 1 = 2

Similarly, other terms can also be calculated.  

Filename: CatalanSeriesRecursive.java

public class CatalanSeriesRecursive
{
// method for calculating the terms Catalan number series
public static long catalanNumbers(int n)
{
               if (n <= 1) // base case
               {
                               return 1;
               }
               long catNo = 0;
               for (int i = 0; i < n; i++)
               {
                               // recusively calculating the terms of the Catalan number series
                               catNo = catNo + (catalanNumbers(i) * catalanNumbers(n - i - 1));
               }
               // returning the result
               return catNo;
}
public static void main(String argvs[])
{
               // Defines the number of terms up to which we are printing the Catalan series
               int noOfTerms = 15;
               System.out.print("The first " + noOfTerms + " terms of Catalan series are: \n");
               // We start from 0th term
               for(int i = 0; i < noOfTerms; i++)
               {
                               // calling the method catalanNumbers() and storing the result
                               long term = catalanNumbers(i);
                               // displaying the terms
                               System.out.print(term + " ");
               }
}  
} 

Output:

 The first 15 terms of Catalan series are:
1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 

Explanation: For each term, starting from the 0th term, we are invoking the method catalnNumbers(), and recursively finding the term of the Catalan series. The recursion used in the code is based on the recursive formula, which we have defined above.

Application of Catalan Numbers

Catalan numbers are used in many interesting problems where counting is required. A few of them are mentioned below.

  • Count the number expressions where n pair of braces are correctly matched.
    • For n = 1, valid expression is (). Thus, the count is 1.
    • For n = 2, valid expressions are () (), (()). Thus, the count is 2.
    • For n = 3, valid expressions are () () (), (()) (), () (()), (() ()), ((())), Thus the count is 5.

  • Count the number of different Binary Search Trees for n nodes.
    • For n = 2, there are 2 different Binary Search Trees. The following diagram demonstrates the same.
  • For n = 3, there are 5 different Binary Search Trees. Observe the following diagram.

Triangular Number Series

Triangular number series is a series of numbers in triangular pattern. A triangular number is a number that counts the number of objects arranged in an equilateral triangle. Thus, the nth triangular number is the equilateral triangle who’s each side is comprised of n dots/ circle. The following diagram represents the same.

The nth triangular number is also the sum of natural numbers from 1 to n. Mathematically, the nth triangular number is represented by T(n) = (n  (n + 1)) / 2. Thus, T(1)  = (1  (1 + 1)) / 2 = (1  2) / 2 = 2 / 2 = 1

T(2) = (2  (2 + 1)) / 2 = (2  3) / 2 = 6 / 2 =  3

T(3) = (3 (3 + 1)) / 2 =  (3  4) / 2 = 12 / 2 = 6

Similarly, other triangular numbers can also be calculated. Now, let us observe the code for generating the triangular numbers.

Using Java for-loop

Filename: TriangularSeriesIterative.java

public class TriangularSeriesIterative
{
public static void main(String argvs[])
{
    // Defines the number of terms up to which we are printing the Triangular series
    int noOfTerms = 20;
    System.out.print("The first " + noOfTerms + " terms of the Triangular series are: \n");
    for(int i = 1; i <= noOfTerms; i++)
    {
             // calculating the term
             int term = (i * (i + 1)) / 2;
                // displaying the term
                System.out.print(term + " ");
    }
}  
} 

Output:

 The first 20 terms of Triangular series are:
1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 210 

Explanation: In the code, we have used Java for-loop for calculating the triangular numbers till the 20th term. In each iteration, we are calculating the triangular number with the help of the mathematical formula define above. Now, let us learn the recursive approach.

Using Recursion

Filename: TriangularSeriesRecursive.java

public class TriangularSeriesRecursive
{
// method for calculating terms of the given series
public static int triangularNo(int n)
{
    // base case
    if(n <= 1) return n;
    // recursively calculating the term
    return n + triangularNo(n - 1);
}
public static void main(String argvs[])
{
    // Defines the number of terms up to which we are printing the Triangular series
    int noOfTerms = 20;
    System.out.print("The first " + noOfTerms + " terms of the Triangular series are: \n");
    for(int i = 1; i <= noOfTerms; i++)
    {
             // calculating the term
             // by invoking the method triangularNo()
             int term = triangularNo(i);
              // displaying the term
              System.out.print(term + " ");
    }
}  
} 

 Output:

 The first 20 terms of Triangular series are:
1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 210 

Explanation: In the code, the Java for-loop is iterating 20 times for displaying the first 20 numbers of the triangular series. In each iteration, the method triangularNo() is called for calculating the terms of the triangular series. In the method triangularNo(), we are recursively calculating the sum of the natural number till the ith term. The ith term is passed as an argument to the method triangularNo(). The recursion is based on the fact that the nth triangular number is the sum of the first n natural numbers.

Square Number Series

Numbers that are perfect square form the square number series. Mathematically, the terms of the Square number series are represented by,

T(n) = n2, where n is the nth term

Thus, for n = 1

T(1) = 12 = 1  1 = 1

For n = 2,

T(2) = 22 = 2  2 = 4

For n = 3,

T(3) = 32 = 3  3 = 9

For n = 4,

T(4) = 42 = 4  4 = 16

In the similar way, we can calculate the other terms of the Square series. Let’s observe the code to generate the terms of the triangular series.

Using Java for-loop

Filename: SquareSeriesIterative.java

public class SquareSeriesIterative
{
public static void main(String argvs[])
{
    // Defines the number of terms up to which we are printing the Square series
    int noOfTerms = 20;
    System.out.print("The first"  + noOfTerms + " terms of the Square series are: \n");
    for(int i = 1; i <= noOfTerms; i++)
    {
             // calculating the term using the formula defined above
             int term = (i * i);
                // displaying the term
                System.out.print(term + " ");
    }
}  
} 

Output:

 The first 20 terms of the Square series are:
1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 

Explanation: In the code, we are printing the first 20 terms of the Square series using the Java for-loop. In the body of the for-loop, we have implemented the mathematical formula defined above.

Using Recursion

Let’s define the recursive relation to generated the square numbers. The recursion relation is:

T(1) = 1   [Base case]

And,

T(n) = (2  (n – 1) + 1) + T(n – 1), for n >= 2

Thus,

T(2) = (2  ( 2 – 1) + 1) + T(2 – 1) = (2  1 + 1) + T(1) = 3 + 1 = 4

T(3) = (2  ( 3 – 1) + 1) + T(3 – 1) = (2  2 + 1) + T(2) = 5 + 4 = 9

T(4) = (2  ( 4 – 1) + 1) + T(4 – 1) = (2  3 + 1) + T(3) = 7 + 9 = 16

The other terms can be calculated in the same way.

Filename: SquareSeriesRecursive.java

public class SquareSeriesRecursive
{
// Method for calculating the terms of
// the Square series recursively
public static int sqrNo(int n)
{
    // handling base case
    if(n == 1) return 1;
    // recursively finding the terms
    return ((2 * (n – 1) + 1) + sqrNo(n – 1));
}
public static void main(String argvs[])
{
    // Defines the number of terms up to which we are printing the Square series
    int noOfTerms = 20;
    System.out.print("The first " + noOfTerms + " terms of the Square series are: \n");
    for(int i = 1; i <= noOfTerms; i++)
    {
             // calculating the terms by calling the method sqrNo()
             int term = sqrNo(i);
                // displaying the term
                System.out.print(term + " ");
    }
}  
} 

Output:

 The first 20 terms of the Square series are:
1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 

Explanation: Similar to the iterative approach, here also, we are printing the first 20 terms of the Square series. In each iteration, we are invoking the method sqrNo() and displaying the results generated by the method sqrNo(). In the method sqrNo(), we are calculating the terms of the Square series using the recursive relation explained above.

Cube Number Series

Numbers that are perfect cubes form the Cube number series. Mathematically, the terms of the Cube numbers series are represented by:

T(n) = n3, where n is the nth term

Thus, for n = 1, we have

T(1) = 13 = 1  1  1 = 1

For n = 2,

T(2) = 23 = 2  2  2 = 8

For n = 3,

T(3) = 33 = 3  3  3 = 27

For n = 4,

T(4) = 43 = 4  4  4 = 64

Similarly, we can easily calculate the other terms of the Cube series.

Now, let’s learn about the program to print the terms of the Cube series. We will start with the iterative approach.

Using for loop

Filename: CubeSeriesIterative.java

public class CubeSeriesIterative
{
public static void main(String argvs[])
{
    // Defines the number of terms up to which we are printing the Cube series
    int noOfTerms = 20;
    System.out.print("The first " + noOfTerms + " terms of the Cube series are: \n");
    for(int i = 1; i <= noOfTerms; i++)
    {
             // calculating the term using the formula defined above
             int term = (i * i * i);
                // displaying the term
                System.out.print(term + " ");
    }
}  
} 

Output:

 The first 20 terms of the Cube series are:
1 8 27 64 125 216 343 512 729 1000 1331 1728 2197 2744 3375 4096 4913 5832 6859 8000 

Explanation: Similar to the iterative approaches of other series, we are calculating the terms of the Cube series with the help of the mathematical formula defined above. This time also, the Java for-loop iterates 20 times.

Now let’s observe how we can do the same thing using recursion.

Using Recursion

Before writing the code, it is important to know about the recursive relation for calculating the terms of the Cube series. The recursive relation is:

T(1) = 1 [Base case]

T(n) = T(n – 1) + 1 + 3  (n – 1)  (n - 1)  1 + 3  (n – 1)  1  1, for n >= 2

Thus, for n = 2, we get

T(2) = T(2 – 1) + 1 + 3  (2 – 1)  (2 – 1)  1 + 3 (2 – 1)  1  1

        = T(1) + 1 + 3  1  1  1 + 3  1  1  1 = 1 + 1 + 3 + 3 = 8

For n = 3,

T(3) = T(3 – 1) + 1 + 3  (3 – 1)  (3 – 1)  1 + 3 (3 – 1)  1  1

        = T(2) + 1 + 3  2  2  1 + 3  2  1  1 = 8 + 1 + 12 + 6 = 27

For n = 4,

T(4) = T(4 – 1) + 1 + 3  (4 – 1)  (4 – 1)  1 + 3 (4 – 1)  1  1

        = T(3) + 1 + 3  3  3  1 + 3  3  1  1 = 27 + 1 + 27 + 9 = 64

In the same way, we can calculate the other terms of the series very easily.

Note: The above recursive relation is derived using the following mathematical identity

(a + 1)3 = a3 + 13 + 3.a2.b + 3.a.b2

The following Java code uses the recursive relation to calculate the terms of the series.

Filename: CubeSeriesRecursion.java

public class CubeSeriesRecursion
{
// Method for calculating the terms of the Cube series
public static int cubeNo(int n)
{
    // base case
    if(n == 1) return 1;
    int num = 0; // contains the final result
    // recursively calculating the terms and storing the result
    num = cubeNo(n-1) + 1 + 3 * (n - 1) * (n - 1) * 1 + 3 * (n - 1) * 1 * 1;
    // returning the final result
    return num;
}
public static void main(String argvs[])
{
    // Defines the number of terms up to which we are printing the Cube series
    int noOfTerms = 20;
    System.out.print("The first " + noOfTerms + " terms of the Cube series are: \n");
    for(int i = 1; i <= noOfTerms; i++)
    {
             // invoking the method cubeNo()
             // and storing the result
             int term = cubeNo(i);
                // displaying the term
                System.out.print(term + " ");
    }
}  
} 

Output:

 The first 20 terms of the Cube series are:
1 8 27 64 125 216 343 512 729 1000 1331 1728 2197 2744 3375 4096 4913 5832 6859 8000 

Explanation: In the code, the Java for-loop is again iterating 20 times, and for each iteration, the method cubeNo() is invoked, which takes the loop variable i in the argument. For each value of the variable i, we are calculating the cube of i using the recursive formula defined above.


Related Topics

Java Math getExponent() Method

The getExponent() method of Math class returns the unbiased exponent of the argument. Syntax: public static int getExponent (double d) Parameters: The parameter ‘d’ represents the double value. Return Value: The getExponent () method returns the...

1 minute read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Java Rename File

Renaming a file is the process of changing its name. Using the renameTo() function of the Java File class, renaming operations are possible. A file can be renamed using Java's renameTo()...

3 minutes read.

How to avoid deadlock in java

Deadlock: A deadlock is an event that never going to occur. In java, deadlock is just a part of the multithreading. It is an environment that allows us to run multiple...

4 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.

How to Convert String to long in Java

How to Convert String to long in java It is used when you want to perform the mathematical operation on the String which contains long number then the conversion from String...

4 minutes read.

Radix Sort in Java

Radix Sort in Java Radix sort in Java uses the digits of the numbers given in the sorted array to sort the numbers. The radix sort uses the place value of...

5 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.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

String Coding Interview Questions in Java

What is String in Java?In Java, a String is a Class that is defined in the java.lang package. It isn't a basic data type like int or long. Character Strings...

5 minutes read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.

Java Swing Time Picker

Prerequisites In this tutorial, we will learn the time picker in java swing. Before learn time picker, we should learn about java swing. Java Swing Introduction The Java Foundation Classes include Java Swing....

5 minutes read.

Java Math.multiplyExact() method in Java

Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to...

2 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.