Sum of square-sums of first n natural numbers

CServer Side ProgrammingProgramming

The sum of square-sums of the first n natural numbers is finding the sum of sum of squares upto n terms. This series finds the sum of each number upto n, and adds this sums to a sum variable.

The sum of square-sum of first 4 natural numbers is −

sum = (12) + (12 + 22 ) + (12 + 22 + 32) + (12 + 22 + 32 + 42 ) = 1 + 5 + 14 + 30 = 50

There are two methods to find the sum of square-sum of first n natural numbers.

1) Using the for loop.

In this method, we will Loop through to every number from 1 to N and find the square sum and then add this square sum to a sum variable. this method requires an iterations for n numbers, so it would be e time consuming for greater 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) Using Mathematical formula

Based on finding the nth term and and general formula for the sequence a mathematical formula is derived to find the sum. the formula to find some of square sums of first n natural number is sum = n*(n+1)*(n+1)*(n+2)/12

Based on this formula we can make 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
raja
Published on 19-Aug-2019 08:41:19
Advertisements