Home > Backend Development > C++ > body text

Sum of squares of first n even numbers in C program

王林
Release: 2023-09-12 15:57:03
forward
1240 people have browsed it

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

Output

Sum of first 12 natural numbers is 2600
Copy after login
Copy after login

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

Output

Sum of first 12 natural numbers is 2600
Copy after login
Copy after login

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!

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