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
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 −
#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; }
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.
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
#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; }
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!