Find the Sum of the series 1/2 – 2/3 + 3/4 – 4/5 + … till N terms
Given a number N, the task is to find the sum of the below series till N terms.
Examples:
Input: N = 6
Output: -0.240476
Input: N = 10
Output: -0.263456
Approach: From the given series, find the formula for Nth term:
1st term = 1/2
2nd term = - 2/3
3rd term = 3/4
4th term = - 4/5
.
.
Nthe term = ((-1)N) * (N / (N + 1))
Therefore:
Nth term of the series
*** QuickLaTeX cannot compile formula:
*** Error message:
Error: Nothing to show, formula is empty
Then iterate over numbers in the range [1, N] to find all the terms using the above formula and compute their sum.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printSeriesSum( int N)
{
double sum = 0;
for ( int i = 1; i <= N; i++) {
if (i & 1) {
sum += ( double )i / (i + 1);
}
else {
sum -= ( double )i / (i + 1);
}
}
cout << sum << endl;
}
int main()
{
int N = 10;
printSeriesSum(N);
return 0;
}
|
Java
class GFG{
static void printSeriesSum( int N)
{
double sum = 0 ;
for ( int i = 1 ; i <= N; i++) {
if (i % 2 == 1 ) {
sum += ( double )i / (i + 1 );
}
else {
sum -= ( double )i / (i + 1 );
}
}
System.out.print(sum + "\n" );
}
public static void main(String[] args)
{
int N = 10 ;
printSeriesSum(N);
}
}
|
Python3
def printSeriesSum(N) :
sum = 0 ;
for i in range ( 1 , N + 1 ) :
if (i & 1 ) :
sum + = i / (i + 1 );
else :
sum - = i / (i + 1 );
print ( sum );
if __name__ = = "__main__" :
N = 10 ;
printSeriesSum(N);
|
C#
using System;
class GFG {
static void printSeriesSum( int N)
{
double sum = 0;
for ( int i = 1; i <= N; i++) {
if ((i & 1)==0) {
sum += ( double )i / (i + 1);
}
else {
sum -= ( double )i / (i + 1);
}
}
Console.WriteLine(sum);
}
public static void Main ( string [] args)
{
int N = 10;
printSeriesSum(N);
}
}
|
Javascript
<script>
function printSeriesSum( N)
{
let sum = 0;
for (let i = 1; i <= N; i++) {
if (i & 1) {
sum += i / (i + 1);
}
else {
sum -= i / (i + 1);
}
}
document.write( sum.toFixed(6) );
}
let N = 10;
printSeriesSum(N);
</script>
|
Time complexity: O(n) for given input n
Auxiliary Space: O(1), since no extra space has been taken.
Last Updated :
07 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...