Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หาพจน์ที่ N ของอนุกรม 1, 3, 12, 60, 360,... ใน C++

หาพจน์ที่ N ของอนุกรม: 1, 3, 12, 60, 360, 2520 ...

ตัวอย่าง: N = 6 → 2520

วิธีแก้ปัญหา (Factorial Pattern)

ค่าเพิ่มขึ้นเร็วมาก เป็นรูปแบบแฟกทอเรียล สังเกตว่าพจน์แรกคือ 2!/2 สูตรทั่วไป:

TN = (N+1)! / 2

ตัวอย่างโค้ด C++

#include <iostream>
using namespace std;

int calcFact(int n) {
    if (n == 1) return 1;
    return n * calcFact(n - 1);
}

int findNTerm(int N) {
    int nthTerm = calcFact(N + 1) / 2;
    return nthTerm;
}

int main() {
    int N = 8;
    cout << N << "th term of the series is " << findNTerm(N);
    return 0;
}

Output

8th term of the series is 181440