Program to find sum of harmonic series in C++


In this problem, we are given three numbers a, d, and n. Our task is to create a program to find sum of harmonic series in C++.

Harmonic progression is a series whose inverse will be an arithmetic progression. I.e. if for a harmonic progression A1, A2, A3.. An, there is an arithmetic progression 1/A1, 1/A2, 1/A3.

So, a general HP is

1/a, 1/(a+d), 1/(a+2d), … 1/(a + nd)

Where 1/a is the first term. And d is the common difference of the reversed AP.

Problem Description − Here, we will be given the first term a, common difference d, and the number of terms n. Of the HP and we need to find the sum of it.

Let’s take an example to understand the problem

Input

a = 3, d = 2, n = 5

Output

0.878211

Explanation

The HP is ⅓, ⅕, 1/7, 1/9, 1/11.

Sum = ⅓ + ⅕ + 1/7 + 1/9 + 1/11 = 0.878211

Solution Approach

We will iterate this nth term and find the value of each term of HP and add it to the sumVar. And return the sumVal at the end.

Algorithm

Initialize − sumVal = 0, term = 0;

  • Step 1 − loop for i -> 1 to n
    • Step 1.1 − find the term, term = 1/( a + (i-1)*(d).
  • Step 1.2 − Update sumVal, sumVal += term.
  • Step 2 − Print sumVal.

Program to illustrate the working of our solution

Example

 Live Demo

#include <iostream>
using namespace std;
float findSeriesSum(int a, int d, int n){
   float sumVal = 0;
   float term = 0;
   for(float i = 1; i <= n; i++){
      term = (1.0)/(float)(a + (i-1)*d);
      sumVal += term;
   }
   return sumVal;
}
int main(){
   int n = 5, a = 3, d = 2;
   cout<<"The sum of HP is "<<findSeriesSum(a, d, n);
   return 0;
}

Output

The sum of HP is 0.878211

One more approach could be using the recursion function to find the sum.

Program to illustrate the working of our solution

Example

 Live Demo

#include <iostream>
using namespace std;
float findSeriesSum(int a, int d, int n){
   if(n == 1){
      return (float)(1.0)/a;
   }
   float term = (1.0)/ (float)(a + (n-1)*d);
   return term + findSeriesSum(a, d, n-1);
}
int main(){
   int n = 5, a = 3, d = 2;
   cout<<"The sum of HP is "<<findSeriesSum(a, d, n);
   return 0;
}

Output

The sum of HP is 0.878211

Updated on: 16-Sep-2020

504 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements