Harmonic series is the inverse of an arithmetic progression. In general, the terms in a harmonic progression can be denoted as
h1 = 1/a, h2 = 1/(a+d), h3 = 1/(a+2d), h4 = 1/(a+3d), …………….., hn = 1/(a+nd).
Where h is the harmonic series, a is arithmetic progression and d is the common difference between arithmetic progression and n is the nth term.
Example 1: (Using while loop)
Java
// Java Program to Generate Harmonic Series class HarmonicSeries { // this is a main function public static void main(String args[]) { // num is the number of values we want in a series int num = 5 ; double result = 0.0 ; System.out.println( "The harmonic series is: " ); // printing the harmonic series till num value // using while loop while (num > 0 ) { // calculating harmonic values result = result + ( double ) 1 / num; // after calculating harmonic value // decrementing num by 1 which means the common // difference is 1 num--; System.out.print(result + ", " ); } } } |
The harmonic series is: 0.2, 0.45, 0.7833333333333333, 1.2833333333333332, 2.283333333333333,
Time complexity: O(n) for given n terms
Auxiliary Space: O(1)
Example 2: (Using for loop)
Java
// Java Program to Generate Harmonic Series class HarmonicSeries { // this is a main function public static void main(String args[]) { // num is the number of values we want in a series int num = 5 ; double result = 0.0 ; System.out.println( "The harmonic series is: " ); // printing the harmonic series till num value // using for loop for ( int i = num; i > 0 ; i--) { // calculating harmonic values result = result + ( double ) 1 / i; System.out.print(result + ", " ); } } } |
The harmonic series is: 0.2, 0.45, 0.7833333333333333, 1.2833333333333332, 2.283333333333333,
Example 3:
Java
// Java Program to Generate Harmonic Series // importing necessary java packages import java.util.Scanner; import java.lang.*; class HarmonicSeries { // this is a main function public static void main(String args[]) { // scanner class is a pre-defined class in java // for taking input from keyboard Scanner in = new Scanner(System.in); System.out.print( "Enter Number: " ); // storing input value in num int num = in.nextInt(); double result = 0.0 ; System.out.println( "The harmonic series is: " ); // printing the harmonic series till num value // using for loop for ( int i = num; i > 0 ; i--) { // calculating harmonic values result = result + ( double ) 1 / i; System.out.print(result + ", " ); } } } |
Output
$ javac HarmonicSeries.java $ java HarmonicSeries Enter Number: 5 The harmonic series is: 0.2, 0.45, 0.7833333333333333, 1.2833333333333332, 2.283333333333333
$ javac HarmonicSeries.java $ java HarmonicSeries Enter Number: 6 The harmonic series is: 0.16666666666666666, 0.3666666666666667, 0.6166666666666667, 0.95, 1.45, 2.45
Time complexity: O(N) to generate series for given N terms
Auxiliary Space: O(1)