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
Release: 2023-08-26 16:05:15
forward
1263 people have browsed it

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>,....
Copy after login

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
Copy after login

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;
}
Copy after login

Output

The sum of series till 3 is 20
Copy after login

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!

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