Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Chương trình C++ tìm số Fibonacci chẵn thứ N

Mô tả bài toán

Cho N, tìm số Fibonacci chẵn thứ N (F0=0, F1=1, F2=1, F3=2...).

Ví dụ

N=4 → Output: 144 (dãy chẵn: 0,2,8,34,144...).

Giải thuật

Mỗi số Fibonacci thứ 3 là chẵn. Dãy số chẵn thỏa En = 4En-1 + En-2 (E0=0, E1=2). Dùng đệ quy hoặc DP.

Mã nguồn C++

#include <iostream>
using namespace std;

int findNthEvenFiboNum(int n) {
    if (n < 1) return n;
    if (n == 1) return 2;
    return 4*findNthEvenFiboNum(n-1) + findNthEvenFiboNum(n-2);
}

int main() {
    int n=5;
    cout << n << "th even fibonacci number is " << findNthEvenFiboNum(n);
    return 0;
}

Đầu ra

5th even fibonacci number is 610