首頁  >  文章  >  後端開發  >  在C編程中,將序列2、6、12、20、30的前N項求和

在C編程中,將序列2、6、12、20、30的前N項求和

WBOY
WBOY轉載
2023-08-26 16:05:151182瀏覽

在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+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>,....

使用數學公式求出第一個和第二個總和

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

範例

#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

以上是在C編程中,將序列2、6、12、20、30的前N項求和的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除