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 1, 4, 15, 24, 45, 60, 92... trong C++

Cho số N. Tìm số hạng thứ N của dãy: 1, 4, 15, 24, 45, 60, 92, 112, ...

Công thức chung (phân biệt chẵn/lẻ)

  • N lẻ: Tn = 2N² - N
  • N chẵn: Tn = 2(N² - N)

Ví dụ

N = 6 (chẵn) → 2×(36-6) = 60

N = 10 (chẵn) → 2×(100-10) = 180

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

#include <iostream>
using namespace std;

int findNTerm(int N) {
    if (N % 2 == 0) return 2 * ((N * N) - N);
    return (2 * (N * N)) - N;
}

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 180