Home >Backend Development >C++ >In C programming, sum the first N items of the sequence 2, 6, 12, 20, 30

In C programming, sum the first N items of the sequence 2, 6, 12, 20, 30

WBOY
WBOYforward
2023-08-26 16:05:151278browse

In C programming, sum the first N items of the sequence 2, 6, 12, 20, 30

To require the sum of this series, we first analyze this series.

The series is: 2,6,12,20,30...

Example

For n = 6
Sum = 112
On analysis, (1+1),(2+4),(3+9),(4+16)...
(1+1<sup>2</sup>), (2+2<sup>2</sup>), (3+3<sup>2</sup>), (4+4<sup>2</sup>), can be divided into two series i.e.
s1:1,2,3,4,5&hellip; andS2: 1<sup>2</sup>,<sup>2</sup>,3<sup>2</sup>,....

Use mathematical formulas to find the sum of the first and second

Sum1 = 1+2+3+4&hellip; , sum1 = n*(n+1)/2
Sum2 = 12+2<sup>2</sup>+3<sup>2</sup>+4<sup>2</sup>&hellip; , sum1 = n*(n+1)*(2*n +1)/6

Example

#include <stdio.h>
int main() {
   int n = 3;
   int sum = ((n*(n+1))/2)+((n*(n+1)*(2*n+1))/6);
   printf("the sum series till %d is %d", n,sum);
   return 0;
}

Output

The sum of series till 3 is 20

The above is the detailed content of In C programming, sum the first N items of the sequence 2, 6, 12, 20, 30. 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