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

หาพจน์ที่ N ของอนุกรม 1, 1, 2, 6, 24... (Factorial) ด้วย C++


ภาพรวมปัญหา

หาพจน์ที่ N ของอนุกรม: 1, 1, 2, 6, 24, 120, 720, ...

ตัวอย่าง

อินพุต

N = 7

เอาต์พุต

720

คำอธิบาย

อนุกรมคือ Factorial: 0!, 1!, 2!, 3!, 4!, 5!, 6! ...
T(N) = (N-1)!

วิธีแก้ปัญหา

คำนวณ Factorial ของ (N-1)

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

#include <iostream>
using namespace std;

int calcNthTerm(int N) {
    if (N <= 1)
        return 1;
    int factorial = 1;
    for (int i = 1; i < N; i++)
        factorial *= i;
    return factorial;
}

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

เอาต์พุต

8th term of the series is 5040

สรุป

อนุกรม Factorial แบบเลื่อน index คำนวณ (N-1)! ได้ใน O(N)