Home > Backend Development > C++ > body text

The sum of the square sums of the first n natural numbers

王林
Release: 2023-09-09 11:53:02
forward
1257 people have browsed it

The sum of the square sums of the first n natural numbers

The sum of the squares of the first n natural numbers is the sum of the squares of up to n terms. This series finds the sum of every number up to n and adds the sum to the sum variable.

The sum of the square sums of the first 4 natural numbers is -

sum = (12) (12 22 ) (12 22 32) (12 22 3 2 4 2 ) = 1 5 14 30 = 50

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

1) Use a for loop.

In this method we will loop through each number from 1 to N and find the sum of squares and then add this sum of squares to the sum variable. This method requires iteration over n numbers, so will be very time consuming for larger numbers.

Example

#include <stdio.h>
int main() {
   int n = 6;
   int sum = 0;
   for (int i = 1; i <= n; i++)
      sum += ((i * (i + 1) * (2 * i + 1)) / 6);
   printf("The square-sum of first %d natural number is %d",n,sum);
   return 0;
}
Copy after login

Output

The square-sum of first 6 natural number is 196
Copy after login
Copy after login

2) Use mathematical formula

based on finding the nth term of the sequence and the general formula , derive mathematical formulas for summing. The formula for finding the sum of the squares of the first n natural numbers is sum = n*(n 1)*(n 1)*(n 2)/12

According to this formula we can write a program to find the sum,

Example

#include <stdio.h>
int main() {
   int n = 6;
   int sum = (n*(n+1)*(n+1)*(n+2))/12;
   printf("The square-sum of first %d natural number is %d",n,sum);
   return 0;
}
Copy after login

Output

The square-sum of first 6 natural number is 196
Copy after login
Copy after login

The above is the detailed content of The sum of the square sums of the first n natural 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