C++ 中 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... 系列的和\n


在這個問題中,我們給定一個數字 n,它是級數 1/(1*2) + 1/(2*3) +…+ 1/(n*(n+1)) 的第 n 項。我們的任務是建立一個程式來找到該級數的和。

讓我們舉個例子來理解這個問題,

輸入

n = 3

輸出

0.75

解釋 - 和 = 1/(1*2) + 1/(2*3) + 1/(3*4) = ½ + ⅙+ 1/12 = (6+2+1)/12 = 9/12 = ¾ = 0.75

解決該問題的一個簡單方法是使用迴圈。並計算級數中每個元素的值。然後將它們新增到 sum 值中。

演算法

Initialize sum = 0
Step 1: Iterate from i = 1 to n. And follow :
   Step 1.1: Update sum, sum += 1/ ( i*(i+1) )
Step 2: Print sum.

示例

程式說明我們解決方案的工作原理,

即時演示

#include <iostream>
using namespace std;
double calcSeriesSum(int n) {
   double sum = 0.0;
   for (int i = 1; i <= n; i++)
   sum += ((double)1/(i*(i+1)));
   return sum;
}
int main() {
   int n = 5;
   cout<<"Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is "<<calcSeriesSum(n);
   return 0;
}

輸出

Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is 0.833333

此解決方案效率不高,因為它使用了迴圈。

解決該問題的一個有效方法是使用級數和的一般公式。

The series is 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + …
n-th terms is 1/n(n+1).
an = 1/n(n+1)
an = ((n+1) - n) /n(n+1)
an = (n+1)/n(n+1) - n/ n(n+1)
an = 1/n - 1/(n+1)
sum of the series is
sum = 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + …
Changing each term as in above formula,
sum = 1/1 - ½ + ½ - ⅓ + ⅓ - ¼ + ¼ -⅕ + …. 1/n - 1/(n+1)
sum = 1 - 1/(n+1)
sum = (n+1 -1) / (n+1) = n/(n+1)

示例

程式說明我們解決方案的工作原理,

即時演示

#include <iostream>
using namespace std;
double calcSeriesSum(int n) {
   return ((double)n/ (n+1));
}
int main() {
   int n = 5;
   cout<<"Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is "<<calcSeriesSum(n);
   return 0;
}

輸出

Sum of the series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... is 0.833333

更新於:2020-08-14

552 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.