Cho số nguyên n. Tính tổng S = 1/(1·2) + 1/(2·3) + ... + 1/(n·(n+1)).
Ví dụ
n = 3: S = 1/2 + 1/6 + 1/12 = 9/12 = 0.75
Cách 1: Vòng lặp O(n)
double sum = 0;
for (int i = 1; i <= n; i++)
sum += 1.0 / (i * (i + 1));
Cách 2: Công thức rút gọn O(1)
Quan sát: 1/(i(i+1)) = 1/i - 1/(i+1).
Tổng hoãn quy (telescoping):
S = (1/1 - 1/2) + (1/2 - 1/3) + ... + (1/n - 1/(n+1)) = 1 - 1/(n+1) = n/(n+1)
Chương trình C++
#include <iostream>
#include <iomanip>
using namespace std;
double calcSeriesSum(int n) {
return (double)n / (n + 1);
}
int main() {
int n = 5;
cout << fixed << setprecision(6)
<< "Tong chuoi = " << calcSeriesSum(n); // 0.833333
return 0;
}
Kết quả
Tong chuoi = 0.833333