ภาพรวมปัญหา
หาพจน์ที่ N ของอนุกรม: 5, 13, 25, 41, 61, ...
ตัวอย่าง
อินพุต
N = 5
เอาต์พุต
61
วิธีแก้ปัญหา
สังเกตรูปแบบ:
N=1: 5 = 1² + 2² N=2: 13 = 2² + 3² N=3: 25 = 3² + 4² N=4: 41 = 4² + 5² N=5: 61 = 5² + 6²
สูตรทั่วไป: T(N) = N² + (N+1)²
โค้ดตัวอย่าง
#include <iostream>
using namespace std;
int calcNthTerm(int N) {
return (N * N) + ((N + 1) * (N + 1));
}
int main() {
int N = 7;
cout << N << "th term of the series is " << calcNthTerm(N);
return 0;
}
เอาต์พุต
7th term of the series is 113
สรุป
คำนวณได้ใน O(1) โดยใช้สูตรปิด (Closed-form formula)