Home >Backend Development >C++ >Sum of squares of first n even numbers in C program

Sum of squares of first n even numbers in C program

王林
王林forward
2023-09-12 15:57:031286browse

Sum of squares of first n even numbers in C program

The sum of the squares of the first n even numbers means, we first find the squares and add them all to get the sum.

There are two ways to find the sum of the squares of the first n even numbers

Use a loop

We can use a loop to iterate from 1 to n, increasing by 1 each time, to find the square And add it to the sum variable −

Example

#include <iostream>
using namespace std;
int main() {
   int sum = 0, n =12;
   for (int i = 1; i <= n; i++)
      sum += (2 * i) * (2 * i);
   cout <<"Sum of first "<<n<<" natural numbers is "<<sum;
   return 0;
}

Output

Sum of first 12 natural numbers is 2600

The complexity of this program increases in the order of 0(n). Therefore, for larger values ​​of n, the code takes time.

Use mathematical formula

In order to solve this problem, a mathematical formula is derived, that is, the sum of even natural numbers is 2n(n 1)(2n 1)/3

Example

#include <iostream>
using namespace std;
int main() {
   int n = 12;
   int sum = (2*n*(n+1)*(2*n+1))/3;
   cout <<"Sum of first "<<n<<" natural numbers is "<<sum;
   return 0;
}

Output

Sum of first 12 natural numbers is 2600

The above is the detailed content of Sum of squares of first n even numbers in C program. 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