ภาพรวมปัญหา
หาพจน์ที่ N ของอนุกรม: 1, 3, 6, 10, 15, 21, 28, ...
ตัวอย่าง
อินพุต
N = 7
เอาต์พุต
28
วิธีแก้ปัญหา
เป็น Triangular Numbers: T(N) = 1 + 2 + ... + N = N(N+1)/2
โค้ดตัวอย่าง
#include <iostream>
using namespace std;
int findNthTerm(int N) {
return N * (N + 1) / 2;
}
int main() {
int N = 8;
cout << "The " << N << "th term of the series is " << findNthTerm(N);
return 0;
}
เอาต์พุต
The 8th term of the series is 36
สรุป
Triangular Numbers สูตรปิด N(N+1)/2 คำนวณ O(1)