Home  >  Article  >  Backend Development  >  The sum of the squares of the first n odd numbers

The sum of the squares of the first n odd numbers

WBOY
WBOYforward
2023-08-31 20:29:091057browse

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 =

Explanation

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.

Example

#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;
}

Output

The sum of square of first 8 odd numbers is 680

Example

#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;
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete