×

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

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

Java Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

Volatile keyword in Java

Multiple threads can change a variable's value by using the volatile keyword. Making classes thread-safe is another application for it. It indicates that using a method or an instance of...

3 minutes read.

Java FileOutputStream

What is FileOutputStream?When we need raw stream data written into a file, we need to look for another option: FileOutputStream. It is used when the file's data is byte-oriented. It comes under...

4 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

Thread Safety and How to Achieve it in Java

Before diving into the topic, let’s just recap the concept of Multithreading provided by Java where we can create and execute multiple threads of the same object. When these multiple...

5 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute 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.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute read.

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates...

4 minutes read.

Compile-time Error in Java

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the...

4 minutes read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.