Sum of the Series 1 + x/1 + x^2/2 + x^3/3 + .. + x^n/n in C++


In this problem, we are given two numbers X and n, which denote a mathematical series. Our task is to create a program to find the sum of the series 1 + x/1 + x^2/2 + x^3/3 + .. + x^n/n.

Let’s take an example to understand the problem,

Input

x = 2 , n = 4

Output

Explanation −

sum= 1 + 2/1 + (2^2)/2 + (2^3)/3 + (2^4)/4
   = 1 + 2 + 4/2 + 8/3 + 16/4
   = 1 + 2 + 2 + 8/3 + 4
   = 9 + 8/3
   = 11.666.

A simple solution is to create the series and find the sum using the base value x and range n. Then return the sum.

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
double calcSeriesSum(int x, int n) {
   double i, total = 1.0;
   for (i = 1; i <= n; i++)
   total += (pow(x, i) / i);
   return total;
}
int main() {
   int x = 3;
   int n = 6;
   cout<<"Sum of the Series 1 + x/1 + x^2/2 + x^3/3 + .. + x^"<<n<<"/"<<n<<" is "<<setprecision(5)   <<calcSeriesSum(x, n);
   return 0;
}

Output

Sum of the Series 1 + x/1 + x^2/2 + x^3/3 + .. + x^6/6 is 207.85

Updated on: 14-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements