# Find sum of Series with n-th term as n^2 - (n-1)^2 in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an integer value N. Our task is to find Sum of Series n^2 - (n-1)^2 upto n terms.

Let's take an example to understand the problem,

Input : N = 3
Output : 6

Explanation

[12 - (0)2] + [22 - (1)2] + [32 - (2)2] = 1 - 0 + 4 - 1 + 9 - 2 = 9

## Solution Approach

A simple approach to solve the problem is finding the general term of the series and then finding the sum till n terms. And calculating the sum using formula will reduce the time to O(1). Also, the result can be huge so modulus of the values needs to be found.

Let's derive the formula for nth term of the series,

$T_{n}\:=\:\mathrm{n^2-(n-1)^2}$

On solving using a2 - b2 formula,

$T_{n}\:=\:\mathrm{(n+n-1)*(n-n+1)}$

$=\:\mathrm{(2*n-1)*(1)}$

$=\:\mathrm{2*n-1}$

Using this we can find the sum till n terms of the series,

$\mathrm{sum}\:=\:\sum(2*n-1)$

$\mathrm{sum}\:=\:2*\sum{n}\:-\:\sum{1}$

$\mathrm{sum}\:=\:2*(n*(n+1))/2-n$

$\mathrm{sum}\:=\:n*(n+1)-n\:=\:n^2\:+\:n\:-\:n\:=\:n^2$

The sum of the series is n2 which is a large number, so mod will be taken.

## Example

Program to illustrate the working of our solution

#include<iostream>
using namespace std;
#define mod 1000000007
long long calcSumNTerms(long long n) {
return ((n%mod)*(n%mod))%mod;
}
int main() {
long long n = 4325353;
cout<<"The sum of series upto n terms is "<<calcSumNTerms(n); return 0;
}

## Output

The sum of series upto n terms is 678443653
Updated on 27-Jan-2022 08:38:47