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 lũy thừa 2 và 3 xen kẽ trong C++

Cho dãy: 1, 1, 2, 3, 4, 9, 8, 27, 16, 81, 32, 243... Tìm số hạng thứ N.

Phân tích

Dãy xen kẽ:

  • Vị trí lẻ: lũy thừa của 2 (2^0, 2^1, 2^2...).
  • Vị trí chẵn: lũy thừa của 3 (3^0, 3^1, 3^2...).

Công thức: N lẻ → 2^(N/2); N chẵn → 3^((N-1)/2).

Mã nguồn C++

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

int findNTerm(int N) {
    if (N % 2 == 0) return pow(3, (N-1)/2);
    else return pow(2, N/2);
}

int main() {
    cout << "9th term: " << findNTerm(9) << endl;  // 16
    cout << "14th term: " << findNTerm(14) << endl; // 729
    return 0;
}

Đầu ra

9th term of the series is 16
14th term of the series is 729