C语言编程中数列2, 6, 12, 20, 30…前N项的和
为了求出这个数列的和,我们首先要分析这个数列。
这个数列是:2, 6, 12, 20, 30…
示例
For n = 6 Sum = 112 On analysis, (1+1),(2+4),(3+9),(4+16)... (1+12), (2+22), (3+32), (4+42), can be divided into two series i.e. s1:1,2,3,4,5… andS2: 12,2,32,....
使用数学公式求前两项的和
Sum1 = 1+2+3+4… , sum1 = n*(n+1)/2 Sum2 = 12+22+32+42… , sum1 = n*(n+1)*(2*n +1)/6
示例
#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; }
输出
The sum of series till 3 is 20
广告