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

更新於:2019年8月9日

283 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.