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

โปรแกรม C++ หาพจน์ที่ N ของอนุกรมที่ f[i] = f[i-1] - f[i-2]


สมมติว่าเรามีอนุกรมที่เรียกว่า f แต่ละพจน์ของ f ปฏิบัติตามกฎนี้ f[i] = f[i-1] - f[i-2] เราต้องหาพจน์ที่ N ของลำดับนี้ f[0] = X และ f[1] = Y ถ้า X = 2 และ Y = 3 และ N = 3 ผลลัพธ์จะเป็น -2

หากเราดูอย่างใกล้ชิด จะมีเกือบหกพจน์ก่อนที่ลำดับจะเริ่มซ้ำตัวเอง ดังนั้นเราจะหาพจน์แรก 6 พจน์ของอนุกรม และพจน์ที่ N จะเท่ากับพจน์ที่ (N mod 6)

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

#include <iostream>
using namespace std;

int searchNthTerm(int x, int y, int n) {
    int terms[6];
    terms[0] = x;
    terms[1] = y;
    for (int i = 2; i <= 5; i++)
        terms[i] = terms[i - 1] - terms[i - 2];
    return terms[n % 6];
}

int main() {
    int x = 2, y = 3, n = 3;
    cout << "Term at index " << n << " is: " << searchNthTerm(x, y, n);
}

ผลลัพธ์

Term at index 3 is: -2