Java Program to Print Series 1,2,9,28,65

How to print this series?

Below is the logic to solve the series,

1 = (0 * 0 * 0) + 1
2 = (1 * 1 * 1) + 1
9 = (2 * 2 * 2) + 1
28 = (3 * 3 * 3) + 1
65 = (4 * 4 * 4) + 1

We are going to see two solutions here to print this series,

Solution #1:

package com.javacodepoint.series;

import java.util.Scanner;

/**
 * Series pattern: 1, 2, 9, 28, 65
 * 
 * @author javacodepoint.com
 *
 */
public class SeriesPattern1 {

	public static void main(String[] args) {
		
		// Create scanner object to read user inputs
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter no. of elements you want in the series: ");
		int n = sc.nextInt();
		
		System.out.print("Series: ");
		for (int i = 0; i < n; i++) {
			
			// Calculate the element of the series
			int element = (i * i * i) + 1;
			
			// Print the element with comma(,) separator
			System.out.print(element + ", ");
		}
	}
}

OUTPUT:

Enter no. of elements you want in the series:
7
Series: 1, 2, 9, 28, 65, 126, 217,

Solution #2:

By using Math.pow() method,

package com.javacodepoint.series;

import java.util.Scanner;

/**
 * Series pattern: 1, 2, 9, 28, 65
 * 
 * @author javacodepoint.com
 *
 */
public class SeriesPattern2 {

	public static void main(String[] args) {
		
		// Create scanner object to read user inputs
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter no. of elements you want in the series: ");
		int n = sc.nextInt();
		
		System.out.print("Series: ");
		for (int i = 0; i < n; i++) {
			
			// Calculate the element of the series
			int element = (int) (Math.pow(i, 3) + 1);
			
			// Print the element with comma(,) separator
			System.out.print(element + ", ");
		}
	}
}

OUTPUT:

Enter no. of elements you want in the series:
6
Series: 1, 2, 9, 28, 65, 126,

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *