ภาพรวมปัญหา
หาผลรวมอนุกรม: Σ n(n+1)(n+2) จาก n=1 ถึง N
ตัวอย่าง
N = 5 → 1×2×3 + 2×3×4 + 3×4×5 + 4×5×6 + 5×6×7 = 6+24+60+120+210 = 420
วิธีแก้ปัญหา 1: วนลูป (O(N))
int calcSeriesSum(int n) {
int sumVar = 0;
for (int i = 1; i <= n; i++)
sumVar += i * (i+1) * (i+2);
return sumVar;
}
วิธีแก้ปัญหา 2: สูตรปิด (O(1))
Σ n(n+1)(n+2) = Σ (n³ + 3n² + 2n)
= Σn³ + 3Σn² + 2Σn
= [n(n+1)/2]² + 3[n(n+1)(2n+1)/6] + 2[n(n+1)/2]
= ¼ n(n+1)(n+2)(n+3)
โค้ด C++ (สูตรปิด)
#include <iostream>
using namespace std;
int calcSeriesSum(int n) {
return (n * (n + 1) * (n + 2) * (n + 3)) / 4;
}
int main() {
int n = 7;
cout << "The sum of series till " << n << " is " << calcSeriesSum(n);
return 0;
}
ผลลัพธ์
N = 7 → 1260