No.8 遞迴快速輸出斐波那契數列

Crius__發表於2020-10-04

No.8 遞迴快速輸出斐波那契數列

規定了範圍為1~90;
主要思想是將已經計算過的值存入陣列,後面大值計算會簡單很多

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

void Fibo(int n, long long F[]) {
	if (n == 1 || n == 2) {
		F[n] = 1;
		return;
	}
	if (F[n] != 0) {
		return;
	}
	else {
		Fibo(n - 1, F);
		Fibo(n - 2, F);
		F[n] = F[n - 1] + F[n - 2];
	}
}

int main() {
	ifstream infile("input.txt");
	int n;
	infile >> n;
	if (n <= 0 || n > 90) {
		cout << "WRONG" << endl << endl;
	}
	else {
		long long F[91] = { 0 };
		Fibo(n, F);
		cout << F[n] << endl << endl;
	}
	return 0;
}

相關文章