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


[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,


On solving using a2 - b2 formula,




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





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


Program to illustrate the working of our solution

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; 


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