ภาพรวมปัญหา
หาพจน์ที่ N ของอนุกรม: 5, 2, 19, 13, 41, 31, 71, 57, ...
ตัวอย่าง
อินพุต
N = 5
เอาต์พุต
41
วิธีแก้ปัญหา
อนุกรมมีสูตรต่างกันสำหรับ index คู่และคี่:
N เป็นเลขคู่ (Even):
T(N) = (N-1)² + N
N เป็นเลขคี่ (Odd):
T(N) = (N+1)² + N
โค้ดตัวอย่าง
#include <iostream>
using namespace std;
int calcNthTerm(int N) {
if (N % 2 == 0)
return ((N - 1) * (N - 1)) + N;
return ((N + 1) * (N + 1)) + N;
}
int main() {
int N = 7;
cout << N << "th term of the series is " << calcNthTerm(N);
return 0;
}
เอาต์พุต
7th term of the series is 71
สรุป
แยกกรณี index คู่/คี่ ใช้สูตรกำลังสองง่ายๆ คำนวณ O(1)