A sequence, whose nth term is defined by: Tn = (n)2 – (n – 1)2.
The task is to calculate the sum of first n term of the sequence i.e find Sn where, Sn = T1 + T2 + ….. + Tn-1 + Tn
Examples:
Input : n = 2 Output : 4 T1 = 12 - 02 = 1 T2 = 22 - 12 = 4 - 1 = 3 So, the sum is 4. Input : n = 1 Output : 1
Method-1:
Simply find each term from T1, T2, …, Tn and add them.
This can be done by running a loop i from 1 to n and for each iteration find Ti and add them to a variable.
Implementation in C++:
// CPP Program to find the
// sum of the first n numbers of the sequence whose
// nth term is the difference
// of the squares of n and n - 1
#include <bits/stdc++.h>
using namespace std;
// Return the sum of the sequence
int sumSequence(int n)
{
int sum = 0;
// For each ith term,
// finding the term and adding it to the result.
for (int i = 1; i <= n; i++)
{
sum += (i * i - (i - 1) * (i - 1));
}
return sum;
}
// Driver Program
int main()
{
int n = 2;
cout << sumSequence(n) << endl;
return 0;
}
Output:
4
Method-2:
We are given that: Tn
= (n)^2 - (n - 1)^2 = n^2 - (n^2 - 2*n + 1) = 2*n - 1
So, nth term can be find by 2*n – 1
Now to calculate Sn
= T1 + T2 + ..... + Tn-1 + Tn = 2*1 - 1 + 2*2 - 1 + 2*3 - 1 + ..... 2*n - 1 = 2*(1 + 2 + .... + n - 1 + n) - n = 2*(n*(n + 1)/2) - n = n*(n + 1) - n = n^2 + n - n = n^2
Implementation in C++:
// CPP Program to find the sum
// of the first n numbers of the sequence whose
// nth term is the difference
// of the squares of n and n - 1
#include <iostream>
using namespace std;
// Return the sum of the sequence
int sumSequence(int n)
{
int sum = 0;
for (int i = 1; i <= n; i++)
{
sum += (i * i - (i - 1) * (i - 1));
}
return sum;
}
// Driver Program
int main()
{
int n = 2;
cout << sumSequence(n) << endl;
return 0;
}
Output:
4
