- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum of series 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2 in C++
In this problem, we are given a number n of the series. Our task is to find the sum of series 1^2 + 3^2 + 5^2 +... + (2*n - 1)^2 for the given value of n.
Let’s take an example to understand the problem,
Input −
n = 5
Output −
84
Explanation −
sum = 1^2 + 3^2 + 5^2 + 7^2 + 9^2 = 1 + 9 + 25 + 49 = 84
A basic approach to solve this problem is by directly applying the formula for the sum of series.
Example
#include <iostream> using namespace std; int calcSumOfSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum += (2*i-1) * (2*i-1); return sum; } int main() { int n = 5; cout<<"The sum of series up to "<<n<<" is "<<calcSumOfSeries(n); return 0; }
Output
The sum of series up to 10 is 165
Another approach to solve is to use the mathematical formula to find the sum of the series.
The sum is,
1^2 + 3^2 + 5^2 + … + (2*n - 1)^2 = {(n * (2*(n-1)) * (2*(n+1)))/3}
Example
#include <iostream> using namespace std; int calcSumOfSeries(int n) { return (n * (2 * n - 1) * (2 * n + 1)) / 3; } int main() { int n = 5; cout<<"The sum of series up to "<<n<<" is "<<calcSumOfSeries(n); return 0; }
Output
The sum of series up to 5 is 165
Advertisements