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

The sum of the squares of the first n odd numbers

WBOY
Release: 2023-08-31 20:29:09
forward
1084 people have browsed it

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 =
Copy after login

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;
}
Copy after login

Output

The sum of square of first 8 odd numbers is 680
Copy after login

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;
}
Copy after login

Output

The sum of square of first 18 odd numbers is 7770
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template