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

Tìm số hạng thứ N của dãy 2, 4, 3, 4, 15... trong C++

Cho số N. Tìm số hạng thứ N của dãy: 2, 4, 3, 4, 15, 0, 14, 16, ...

Phân tích

Viết dưới dạng N × f(N): 1×2, 2×2, 3×1, 4×1, 5×3, 6×0, ...

Quan sát: f(N) = (N%2) + (N%3)

Công thức chung

Tn = N × ((N % 2) + (N % 3))

Ví dụ

N = 9 → 9 × (1 + 0) = 9

N = 10 → 10 × (0 + 1) = 10

Ví dụ minh họa (C++)

#include <iostream>
using namespace std;

int findNTerm(int N) {
    int nthTerm = N * ((N % 2) + (N % 3));
    return nthTerm;
}

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

Đầu ra

10th term of the series is 10