Home >Backend Development >C++ >The sum of the square sums of the first n natural numbers

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

王林
王林forward
2023-09-09 11:53:021292browse

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;
}

Output

The square-sum of first 6 natural number is 196

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;
}

Output

The square-sum of first 6 natural number is 196

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete