Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Chương trình C++ tìm số hạng thứ N của dãy 1, 4, 15, 72, 420…

Giới thiệu

Cho số nguyên N. Tìm số hạng thứ N của dãy: 1, 4, 15, 72, 420…

Ví dụ minh họa

Đầu vào

N = 4

Đầu ra

72

Phân tích dãy

Dãy có dạng: 1!×1, 2!×2, 3!×2.5, 4!×3, 5!×3.5… Hệ số là (N+2)/2.

Công thức chung: T(N) = N! × (N + 2) / 2

Chương trình minh họa

#include <iostream>
using namespace std;

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

int calcNthTerm(int N) {
    return calcFactorial(N) * (N + 2) / 2;
}

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

Đầu ra

7th term of the series is 22680