ภาพรวมปัญหา
หาพจน์ที่ N ของอนุกรม: 3, 9, 21, 41, 71, ...
ตัวอย่าง
อินพุต
N = 7
เอาต์พุต
169
วิธีแก้ปัญหา
สังเกต: T(N) = Σi² + Σi + 1 = n(n+1)(2n+1)/6 + n(n+1)/2 + 1
โค้ดตัวอย่าง
#include <iostream>
using namespace std;
int findNthTerm(int n) {
return (n * (n + 1) * (2 * n + 1)) / 6 + (n * (n + 1)) / 2 + 1;
}
int main() {
int N = 12;
cout << "The " << N << "th term of the series is " << findNthTerm(N);
return 0;
}
เอาต์พุต
The 12th term of the series is 729
สรุป
ผลรวมของกำลังสองบวกผลรวมธรรมชาติบวก 1 คำนวณ O(1) ด้วยสูตรปิด