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 a, b, b, c, c, c... trong C++

Cho dãy: a, b, b, c, c, c, d, d, d, d... (ký tự thứ i xuất hiện i lần). Tìm ký tự thứ N.

Phân tích

Tổng số ký tự đến ký tự thứ k là k(k+1)/2. Tìm k nhỏ nhất sao cho k(k+1)/2 >= N. Xấp xỉ k ≈ sqrt(2N).

Mã nguồn C++

#include <iostream>
#include <cmath>
using namespace std;

char findNTerm(int N) {
    int n = sqrt(2 * N);
    // Điều chỉnh nếu cần
    while (n*(n+1)/2 < N) n++;
    return 'a' + n - 1;
}

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

Đầu ra

54th term of the series is k