Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Sum of series 1^2 + 3^2 + 5^2 + . . . + (2*n – 1)^2
A series is a sequence of numbers that follow a specific mathematical pattern. The series 1² + 3² + 5² + ... + (2*n-1)² represents the sum of squares of the first n odd numbers.
This series has a special property − it follows the formula: Sum = n²(2n² - 1)/3. However, we can also calculate it using loops by adding each term individually.
Syntax
Sum = n²(2n² - 1)/3 // Or using loop: sum += (2*i - 1) * (2*i - 1)
Method 1: Using Loop
This approach calculates the sum by iterating through each odd number and adding its square −
#include <stdio.h>
int main() {
int i, n, sum = 0;
n = 7;
for (i = 1; i <= n; i++) {
sum = sum + (2 * i - 1) * (2 * i - 1);
}
printf("The sum of series 1^2 + 3^2 + ... + %d^2 is %d<br>", 2*n-1, sum);
return 0;
}
The sum of series 1^2 + 3^2 + ... + 13^2 is 819
Method 2: Using Formula
For better efficiency, we can use the mathematical formula directly −
#include <stdio.h>
int main() {
int n, sum;
n = 7;
sum = (n * n * (2 * n * n - 1)) / 3;
printf("Using formula: Sum = %d<br>", sum);
printf("Series: ");
for (int i = 1; i <= n; i++) {
printf("%d^2", 2*i-1);
if (i < n) printf(" + ");
}
printf(" = %d<br>", sum);
return 0;
}
Using formula: Sum = 819 Series: 1^2 + 3^2 + 5^2 + 7^2 + 9^2 + 11^2 + 13^2 = 819
Comparison
| Method | Time Complexity | Space Complexity | Advantage |
|---|---|---|---|
| Loop Method | O(n) | O(1) | Easy to understand |
| Formula Method | O(1) | O(1) | Most efficient |
Conclusion
The sum of squares of first n odd numbers can be calculated using either iterative approach or direct formula. The formula method is more efficient with constant time complexity.
Advertisements
