Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หาพจน์ที่ N ของอนุกรมกำลัง 2 และกำลัง 3 สลับกัน 1, 1, 2, 3, 4, 9, 8, 27... ใน C++

หาพจน์ที่ N ของอนุกรม: 1, 1, 2, 3, 4, 9, 8, 27, 16, 81, 32, 243, 64, 729, 128, 2187, 256, ...

ตัวอย่าง: N = 6 → 9, N = 13 → 64

วิธีแก้ปัญหา (Mixed Series: Powers of 2 and 3)

อนุกรมสลับกันระหว่างกำลังของ 2 และกำลังของ 3:

  • ตำแหน่งคี่: กำลังของ 2 → 2⁰, 2¹, 2², 2³, ... (1, 2, 4, 8, 16, 32, 64, 128, 256...)
  • ตำแหน่งคู่: กำลังของ 3 → 3⁰, 3¹, 3², 3³, ... (1, 3, 9, 27, 81, 243, 729...)

สูตร: - ถ้า N คี่: TN = 2N/2 - ถ้า N คู่: TN = 3(N-1)/2

ตัวอย่างโค้ด 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() {
    int N = 9;
    cout << N << "th term of the series is " << findNTerm(N) << endl;
    N = 14;
    cout << N << "th term of the series is " << findNTerm(N);
    return 0;
}

Output

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