Sum of square of first n odd numbers

The sum of squares of first n odd numbers is a mathematical series where we calculate the squares of the first n odd numbers and add them together. The first n odd numbers are: 1, 3, 5, 7, 9, 11, ... and their squares form the series: 12, 32, 52, 72, 92, 112, ... which equals 1, 9, 25, 49, 81, 121, ...

Syntax

sum = n(2n+1)(2n-1)/3 = n(4n² - 1)/3

Where n is the count of odd numbers to consider.

Method 1: Using Loop Iteration

This approach calculates each odd number, squares it, and adds to the sum −

#include <stdio.h>

int main() {
    int n = 4;
    int sum = 0;
    
    for (int i = 1; i <= n; i++) {
        int odd = 2 * i - 1;
        sum += odd * odd;
    }
    
    printf("First %d odd numbers: ", n);
    for (int i = 1; i <= n; i++) {
        printf("%d ", 2 * i - 1);
    }
    printf("<br>");
    
    printf("Sum of squares: 1² + 3² + 5² + 7² = %d<br>", sum);
    return 0;
}
First 4 odd numbers: 1 3 5 7 
Sum of squares: 1² + 3² + 5² + 7² = 84

Method 2: Using Mathematical Formula

This approach uses the direct formula n(4n² - 1)/3 for O(1) time complexity −

#include <stdio.h>

int main() {
    int n = 8;
    int sum = (n * (4 * n * n - 1)) / 3;
    
    printf("Using formula for n = %d:<br>", n);
    printf("Sum = %d(4×%d² - 1)/3 = %d(%d - 1)/3 = %d<br>", 
           n, n, n, 4 * n * n, sum);
    
    return 0;
}
Using formula for n = 8:
Sum = 8(4×8² - 1)/3 = 8(256 - 1)/3 = 680

Comparison

Method Time Complexity Space Complexity Best For
Loop Iteration O(n) O(1) Understanding the concept
Mathematical Formula O(1) O(1) Efficiency and large values

Key Points

  • The nth odd number is given by the formula: 2n - 1
  • The direct formula n(4n² - 1)/3 provides instant results
  • For large values of n, the mathematical formula is significantly faster

Conclusion

Both methods calculate the sum of squares of first n odd numbers correctly. The mathematical formula approach is preferred for its O(1) time complexity, especially for large values of n.

Updated on: 2026-03-15T11:34:21+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements