![]() |
VOOZH | about |
Given a number N. The task is to find the Nth Harmonic Number.
Let the nth harmonic number be Hn.
The harmonic series is as follows:
H1 = 1
H2 = H1 + 1/2
H3 = H2 + 1/3
H4 = H3 + 1/4
.
.
.
Hn = Hn-1 + 1/n
Examples:
Input : N = 5 Output : 2.45 Input : N = 9 Output : 2.71786
The idea is to traverse from H1 and then consecutively keep finding H2 from H1, H3 from H2 ..... and so on.
Below is the program to find N-th Harmonic Number:
2.71786
Time Complexity: O(N)
Auxiliary Space: O(1) as using constant space, since no extra space has been taken.
Approach 2: Dynamic Programming:
The DP approach is better than the simple iterative approach because it avoids recomputing the sum from scratch every time. In the simple iterative approach, we add each term of the harmonic series from 1 to N one by one in every iteration. This means that we perform N-1 additions in total, which can be time-consuming for large values of N.
we only need to perform N-1 additions once and store the results in the harmonic vector. Then, we can simply access the N-th Harmonic number from the vector in constant time, which is much faster than recomputing the sum from scratch every time.
2.71786
Time Complexity: O(N)
Auxiliary Space: O(1)