Home > Article > Backend Development > The sum of the squares of the first n odd numbers
The series of squares of the first n odd numbers takes the square of the first n odd numbers in the series.
The series is: 1,9,25,49,81,121…
The series can also be written as- 12, 32 , 52, 72, 9 2, 112….
The sum of this series is A mathematical formula-
n(2n 1) (2n-1)/ 3= n(4n2 - 1)/3
For example,
Input: N = 4 Output: sum =
12 32 52 72 = 1 9 25 49 = 84
Using the formula, sum = 4(4(4)2- 1)/3 = 4(64-1)/3 = 4(63)/3 = 4*21 = 84 Both methods is good, but the method using mathematical formulas is better because it doesn't use looks, thus reducing the time complexity.
#include <stdio.h> int main() { int n = 8; int sum = 0; for (int i = 1; i <= n; i++) sum += (2*i - 1) * (2*i - 1); printf("The sum of square of first %d odd numbers is %d",n, sum); return 0; }
The sum of square of first 8 odd numbers is 680
#include <stdio.h> int main() { int n = 18; int sum = ((n*((4*n*n)-1))/3); printf("The sum of square of first %d odd numbers is %d",n, sum); return 0; }
The sum of square of first 18 odd numbers is 7770
The above is the detailed content of The sum of the squares of the first n odd numbers. For more information, please follow other related articles on the PHP Chinese website!