Java Program to Generate Harmonic Series
Last Updated :
12 Sep, 2022
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
class HarmonicSeries {
public static void main(String args[])
{
int num = 5 ;
double result = 0.0 ;
System.out.println( "The harmonic series is: " );
while (num > 0 ) {
result = result + ( double ) 1 / num;
num--;
System.out.print(result + ", " );
}
}
}
|
Output
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
class HarmonicSeries {
public static void main(String args[])
{
int num = 5 ;
double result = 0.0 ;
System.out.println( "The harmonic series is: " );
for ( int i = num; i > 0 ; i--) {
result = result + ( double ) 1 / i;
System.out.print(result + ", " );
}
}
}
|
Output
The harmonic series is:
0.2, 0.45, 0.7833333333333333, 1.2833333333333332, 2.283333333333333,
Example 3:
Java
import java.util.Scanner;
import java.lang.*;
class HarmonicSeries {
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print( "Enter Number: " );
int num = in.nextInt();
double result = 0.0 ;
System.out.println( "The harmonic series is: " );
for ( int i = num; i > 0 ; i--) {
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)
Share your thoughts in the comments
Please Login to comment...