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

หาพจน์ที่ N ของอนุกรมผสม Fibonacci และเฉพาะ 0, 2, 1, 3, 1, 5, 2, 7, 3... ใน C++

หาพจน์ที่ N ของอนุกรม: 0, 2, 1, 3, 1, 5, 2, 7, 3, ...

ตัวอย่าง: N = 7 → 2

วิธีแก้ปัญหา (Mixed Series: Fibonacci + Prime)

อนุกรมนี้ผสม 2 อนุกรมย่อย:

  • ตำแหน่งคี่ (1,3,5...): อนุกรมฟีโบนัชชี 0, 1, 1, 2, 3, ...
  • ตำแหน่งคู่ (2,4,6...): จำนวนเฉพาะ 2, 3, 5, 7, ...

สูตร: - ถ้า N คี่: พจน์ที่ (N/2) ของฟีโบนัชชี - ถ้า N คู่: พจน์ที่ (N/2) ของจำนวนเฉพาะ

ตัวอย่างโค้ด C++

#include <iostream>
using namespace std;

int findNthPrimeTerm(int n) {
    int primeCount = 0;
    for (int i = 2; ; i++) {
        int isPrime = 1;
        for (int j = 2; j <= i/2; j++) {
            if (i % j == 0) { isPrime = 0; break; }
        }
        if (isPrime) primeCount++;
        if (primeCount == n) return i;
    }
    return -1;
}

int FibonacciNthTerm(int n) {
    if (n == 0) return 0;
    if (n == 1) return 1;
    int nthTerm = 1, last = 0;
    for (int i = 2; i <= n; i++) {
        nthTerm += last;
        last = nthTerm - last;
    }
    return nthTerm;
}

int findNTerm(int N) {
    if (N % 2 == 0) return findNthPrimeTerm(N / 2);
    else return FibonacciNthTerm(N / 2);
}

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

Output

13th term of the series is 8
4th term of the series is 3