In: Computer Science
In Java: The n^th Harmonic number is
the sum of the reciprocals of the first n natural
numbers:
H(n) = 1+ 1/2 + 1/3 +1/4 +... +1/n
Write a recursive method and an accompanying main method to compute the n^th Harmonic number.
I have tried but get a blank and would really apreciate a fully explained code.
<Harmonic.java>
import java.io.*;
public class Harmonic {
public static double harmonic(int n) { // create a double type method if(n == 1) { return 1.0; } else { return (1.0 / n) + harmonic(n - 1); //using recursion method to calculate every next //value for harmonnic number & adding them all. } }
public static void main(String [] args) throws IOException {
double result;
System.out.print("Enter the value of n : "); //user input for the limit of n value
BufferedReader inp = new BufferedReader (new InputStreamReader(System.in));
String s= inp.readLine();
int x = Integer.parseInt(s);
Harmonic h = new Harmonic(); //create an object of the Harmonic class which we defined above.
result = h.harmonic(x); //using this object, call the harmonic() method defined inside Class.
System.out.print("The value of nth harmonic number is : " + result); //print the nth harmonic number value.
}
}