Trong bài toán này, ta được cho số n của chuỗi. Nhiệm vụ: tìm tổng chuỗi 1² + 3² + 5² + ... + (2n-1)² cho n cho trước.
Ví dụ minh họa
Đầu vào** –
n = 5
Đầu ra** –
84
Giải thích** –
sum = 1² + 3² + 5² + 7² + 9² = 1 + 9 + 25 + 49 + 81 = 165 (Lưu ý: ví dụ gốc ghi 84 nhưng tính ra 165, có thể n=4 cho 84)
Cách cơ bản: áp dụng công thức trực tiếp bằng vòng lặp.
Ví dụ
#include <iostream>
using namespace std;
int calcSumOfSeries(int n) {
int sum = 0;
for (int i = 1; i <= n; i++)
sum += (2*i-1) * (2*i-1);
return sum;
}
int main() {
int n = 5;
cout << "The sum of series up to " << n << " is " << calcSumOfSeries(n);
return 0;
}
Đầu ra
The sum of series up to 10 is 165
Cách khác: dùng công thức toán học đóng gói.
Tổng = 1² + 3² + 5² + ... + (2n-1)² = n(2n-1)(2n+1)/3
Ví dụ
#include <iostream>
using namespace std;
int calcSumOfSeries(int n) {
return (n * (2 * n - 1) * (2 * n + 1)) / 3;
}
int main() {
int n = 5;
cout << "The sum of series up to " << n << " is " << calcSumOfSeries(n);
return 0;
}
Đầu ra
The sum of series up to 5 is 165