88.3k views
0 votes
The nth harmonic number is defined non-recursively as: 1 +1/2 + 1/3 + 1/4 + ... + 1/n. Come up with a recursive definition and use it to guide you to write a function definition for a double -valued function named harmonic that accepts an int parameters n and recursively calculates and returns the nth harmonic number.

User Bharadwaj
by
7.6k points

1 Answer

2 votes

A recursive definition of the nth harmonic number can be expressed as:

Hn = Hn-1 + 1/n

where Hn is the nth harmonic number and Hn-1 is the (n-1)th harmonic number.

Using this definition, we can write a recursive function definition for the harmonic function in Java:

java

Copy code

public static double harmonic(int n) {

if (n == 1) {

return 1.0;

} else {

return harmonic(n - 1) + 1.0 / n;

}

}

In this function, we check if n is equal to 1. If it is, we return 1.0 as the first harmonic number. Otherwise, we call the harmonic function recursively with n - 1 to calculate the (n-1)th harmonic number, and add 1/n to it to get the nth harmonic number.

We can then test the function by calling it with various values of n:

css

Copy code

System.out.println(harmonic(1)); // output: 1.0

System.out.println(harmonic(2)); // output: 1.5

System.out.println(harmonic(3)); // output: 1.8333333333333333

System.out.println(harmonic(4)); // output: 2.083333333333333

The harmonic function recursively calculates the nth harmonic number by adding 1/n to the (n-1)th harmonic number.

User Treeface
by
7.6k points