#include <stdio.h> #include <stdlib.h> #define NUM 10 //若是NUM很大的話,應該申請的動態內存要用long類型吧? int main() { int i; int *pFib = NULL; //在main中,申請一塊內存,用於存儲Fib數列的各個值; pFib = malloc(NUM * sizeof(int)); for (i = 0; i < NUM; i++) pFib[i] = 0; for (i = 1; i <= NUM; i++) printf("Fib(%d)=%d\n",i,Fib(i,pFib)); free(pFib); return 0; } long int Fib(int N,int *pFib) { if (N <= 1) { if (pFib[N] == 0) pFib[N] = 1; return pFib[N]; } else { if (pFib[N - 1] == 0) pFib[N - 1] = Fib(N - 1, pFib); if (pFib[N - 2] == 0) pFib[N - 2] = Fib(N - 2, pFib); return pFib[N - 1] + pFib[N - 2]; } }
## 經過將已經求過的FIB數列保存起來,能夠大大縮減運行時間。spa