Open In App

Program to find the Nth Harmonic Number

Last Updated : 20 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:
 

C++




// CPP program to find N-th Harmonic Number
 
#include <iostream>
using namespace std;
 
// Function to find N-th Harmonic Number
double nthHarmonic(int N)
{
    // H1 = 1
    float harmonic = 1.00;
 
    // loop to apply the formula
    // Hn = H1 + H2 + H3 ... + Hn-1 + Hn-1 + 1/n
    for (int i = 2; i <= N; i++) {
        harmonic += (float)1 / i;
    }
 
    return harmonic;
}
 
// Driver Code
int main()
{
    int N = 8;
     
    cout<<nthHarmonic(N);
     
    return 0;
}


Java




// Java program to find N-th Harmonic Number
 
import java.io.*;
 
class GFG {
     
// Function to find N-th Harmonic Number
static double nthHarmonic(int N)
{
    // H1 = 1
    float harmonic = 1;
 
    // loop to apply the formula
    // Hn = H1 + H2 + H3 ... + Hn-1 + Hn-1 + 1/n
    for (int i = 2; i <= N; i++) {
        harmonic += (float)1 / i;
    }
 
    return harmonic;
}
 
// Driver Code
 
    public static void main (String[] args) {
            int N = 8;
     
    System.out.print(nthHarmonic(N));
     
    }
}
// This code is contributed
// by ajit


Python 3




# Python3 program to find
# N-th Harmonic Number
 
# Function to find N-th Harmonic Number
def nthHarmonic(N) :
 
    # H1 = 1
    harmonic = 1.00
 
    # loop to apply the formula
    # Hn = H1 + H2 + H3 ... +
    # Hn-1 + Hn-1 + 1/n
    for i in range(2, N + 1) :
        harmonic += 1 / i
 
    return harmonic
     
# Driver code    
if __name__ == "__main__" :
 
    N = 8
    print(round(nthHarmonic(N),5))
 
# This code is contributed by ANKITRAI1


C#




// C# program to find N-th Harmonic Number
using System;
 
class GFG
{
     
// Function to find N-th Harmonic Number
static double nthHarmonic(int N)
{
    // H1 = 1
    float harmonic = 1;
 
    // loop to apply the formula
    // Hn = H1 + H2 + H3 ... +
    // Hn-1 + Hn-1 + 1/n
    for (int i = 2; i <= N; i++)
    {
        harmonic += (float)1 / i;
    }
 
    return harmonic;
}
 
// Driver Code
static public void Main ()
{
    int N = 8;
     
    Console.Write(nthHarmonic(N));
}
}
 
// This code is contributed
// by Raj


PHP




<?php
// PHP program to find
// N-th Harmonic Number
 
// Function to find N-th
// Harmonic Number
function nthHarmonic($N)
{
    // H1 = 1
    $harmonic = 1.00;
 
    // loop to apply the formula
    // Hn = H1 + H2 + H3 ... +
    // Hn-1 + Hn-1 + 1/n
    for ($i = 2; $i <= $N; $i++)
    {
        $harmonic += (float)1 / $i;
    }
 
    return $harmonic;
}
 
// Driver Code
$N = 8;
echo nthHarmonic($N);
     
// This code is contributed
// by Shivi_Aggarwal
?>


Javascript




<script>
 
 
// Javascript program to find
// N-th Harmonic Number
 
// Function to find N-th
// Harmonic Number
function nthHarmonic(N)
{
    // H1 = 1
    let harmonic = 1.00;
 
    // loop to apply the formula
    // Hn = H1 + H2 + H3 ... +
    // Hn-1 + Hn-1 + 1/n
    for (let i = 2; i <= N; i++)
    {
        harmonic += parseFloat(1) / i;
    }
 
    return harmonic;
}
 
// Driver Code
 
let N = 8;
document.write( nthHarmonic(N).toFixed(5));
 
// This code is contributed by bobby
 
</script>


Output

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.

C++




#include <iostream>
#include <vector>
using namespace std;
 
// Function to find N-th Harmonic Number
double nthHarmonic(int N)
{
// H1 = 1
vector<double> harmonic(N+1);
harmonic[1] = 1.0;
  // loop to apply the formula
// Hn = H1 + H2 + H3 ... + Hn-1 + Hn-1 + 1/n
for (int i = 2; i <= N; i++) {
    harmonic[i] = harmonic[i-1] + (double)1 / i;
}
 
return harmonic[N];
}
 
// Driver Code
int main()
{
int N = 8;
  cout<<nthHarmonic(N);
 
return 0;
}


Java




import java.util.*;
 
public class HarmonicNumber {
    // Function to find N-th Harmonic Number
    public static double nthHarmonic(int N) {
        // H1 = 1
        List<Double> harmonic = new ArrayList<>();
        harmonic.add(0.0);  // Add a dummy value to align with the C++ vector indexing
        harmonic.add(1.0);
 
        // loop to apply the formula
        // Hn = H1 + H2 + H3 ... + Hn-1 + Hn-1 + 1/n
        for (int i = 2; i <= N; i++) {
            harmonic.add(harmonic.get(i-1) + 1.0 / i);
        }
 
        return harmonic.get(N);
    }
 
    // Driver Code
    public static void main(String[] args) {
        int N = 8;
        System.out.println(nthHarmonic(N));
    }
}


Python3




def nthHarmonic(N):
    # H1 = 1
    harmonic = [0.0]*(N+1)
    harmonic[1] = 1.0
 
    # loop to apply the formula
    # Hn = H1 + H2 + H3 ... + Hn-1 + Hn-1 + 1/n
    for i in range(2, N+1):
        harmonic[i] = harmonic[i-1] + 1.0 / i
 
    return harmonic[N]
 
# Driver Code
N = 8
print(nthHarmonic(N))


C#




using System;
 
class HarmonicNumber {
    // Function to find N-th Harmonic Number
    static double nthHarmonic(int N) {
        // H1 = 1
        double[] harmonic = new double[N+1];
        harmonic[1] = 1.0;
 
        // loop to apply the formula
        // Hn = H1 + H2 + H3 ... + Hn-1 + Hn-1 + 1/n
        for (int i = 2; i <= N; i++) {
            harmonic[i] = harmonic[i-1] + 1.0 / i;
        }
 
        return harmonic[N];
    }
 
    // Driver Code
    static void Main(string[] args) {
        int N = 8;
        Console.WriteLine(nthHarmonic(N));
    }
}


Javascript




// Function to find N-th Harmonic Number
function nthHarmonic(N) {
    // H1 = 1
    const harmonic = new Array(N + 1);
    harmonic[1] = 1.0;
    // loop to apply the formula
    // Hn = H1 + H2 + H3 ... + Hn-1 + Hn-1 + 1/n
    for (let i = 2; i <= N; i++) {
        harmonic[i] = harmonic[i - 1] + (1 / i);
    }
 
    return harmonic[N];
}
 
// Driver Code
const N = 8;
console.log(nthHarmonic(N));


Output

2.71786

Time Complexity: O(N)

Auxiliary Space: O(1) 

 



Similar Reads

Program to find sum of harmonic series
Harmonic series is inverse of a arithmetic progression. In general, the terms in a harmonic progression can be denoted as 1/a, 1/(a + d), 1/(a + 2d), 1/(a + 3d) .... 1/(a + nd). As Nth term of AP is given as ( a + (n – 1)d). Hence, Nth term of harmonic progression is reciprocal of Nth term of AP, which is 1/(a + (n – 1)d), where "a" is the 1st term
5 min read
Program for harmonic mean of numbers
Given an array of elements, find harmonic mean of numbers. Examples: Input : arr[] = {2.0, 1.0} Output : 1.3333 Harmonic mean = 2/(1/2.0 + 1/1.0) = (2 * 2)/3 = 1.333 Input : arr[] = {13.5, 14.5, 14.8, 15.2, 16.1} Output : 14.7707 Harmonic mean is used when average of rates is required, below is the formula.Harmonic mean of n numbers x1, x2, x3, . .
8 min read
Find Harmonic mean using Arithmetic mean and Geometric mean
Given two numbers, first calculate arithmetic mean and geometric mean of these two numbers. Using the arithmetic mean and geometric mean so calculated, find the harmonic mean between the two numbers. Examples: Input : a = 2 b = 4 Output : 2.666 Input : a = 5 b = 15 Output : 7.500 Arithmetic Mean: Arithmetic Mean 'AM' between two numbers a and b is
5 min read
Find a sequence of distinct integers whose Harmonic Mean is N
Given an integer N, the task is to find a sequence of distinct integers whose Harmonic Mean is N itself. In case such a sequence doesn't exist, print -1. Examples: Input: N = 5Output: {3, 4, 5, 6, 20} Explanation: Given sequence is the correct answer because 5/(1/3​+1/4+1/5​+1/6​+1/20)​=5. Note that there are other possible sequences as well. For e
6 min read
Harmonic progression Sum
Given the first element of the progression 'a', common difference between the element 'd' and number of terms in the progression 'n', where [Tex]n, d, a \in [1, 100000] [/Tex]. The task is to generate harmonic progression using the above set of information.Examples: Input : a = 12, d = 12, n = 5 Output : Harmonic Progression : 1/12 1/24 1/36 1/48 1
10 min read
Leibniz harmonic triangle
The Leibniz harmonic triangle is a triangular arrangement of unit fractions in which the outermost diagonals consist of the reciprocals of the row numbers and each inner cell is the cell diagonally above and to the left minus the cell to the left. To put it algebraically, L(r, 1) = 1/r, where r is the number of the row, starting from 1, and c is th
7 min read
Harmonic Progression
A sequence of numbers is called a Harmonic progression if the reciprocal of the terms are in AP. In simple terms, a, b, c, d, e, f are in HP if 1/a, 1/b, 1/c, 1/d, 1/e, 1/f are in AP. For example, 1/a, 1/(a+d), 1/(a+2d), and so on are in HP because a, a + d, a + 2d are in AP. Fact about Harmonic Progression : In order to solve a problem on Harmonic
7 min read
Summation of floor of harmonic progression
Given an integer N, the task is to find the summation of the harmonic series [Tex]\sum_{i=1}^{n} \lfloor{n/i}\rfloor [/Tex]. Examples: Input: N = 5 Output: 10 floor(3/1) + floor(3/2) + floor(3/3) = 3 + 1 + 1 = 5Input: N = 20 Output: 66 Naive approach: Run a loop from 1 to N and find the summation of the floor values of N / i. Time complexity of thi
4 min read
Check whether nodes of Binary Tree form Arithmetic, Geometric or Harmonic Progression
Given a binary tree, the task is to check whether the nodes in this tree form an arithmetic progression, geometric progression or harmonic progression.Examples: Input: 4 / \ 2 16 / \ / \ 1 8 64 32 Output: Geometric Progression Explanation: The nodes of the binary tree can be used to form a Geometric Progression as follows - {1, 2, 4, 8, 16, 32, 64}
17 min read
Program to find the Nth number of the series 2, 10, 24, 44, 70.....
Given a number N, the task is to find the Nth (N may be up to 10^18) term of this series: 2, 10, 24, 44, 70..... The answer can be very large so print answer under modulo 10^9+9. Examples: Input: N = 2 Output: 10 Input: N = 5 Output: 70 Approach:The formula for Nth term will be: Nth term = 3*n*n - n Below is the implementation of the above approach
4 min read