fibo數列第n項
02-12
fibo數列第n項
求fibo數列第n項,其中第0項為0,第1項為1,從第2項開始的值是前2項的值的和.
遞歸解法:
#include <stdio.h>long fibo(int n){if(n<=0) return 0;if(n==1) return 1;return fibo(n-1)+fibo(n-2);} int main(){int n = 10;long fib = fibo(n);printf("%d
",fib);return 0;}
迭代解法:
#include <stdio.h>long fibo(int n){int result[2]={0,1};if(n<2) return result[n];long fib1 = 0;long fib2 = 1;long fibN = 0;for(int i=2;i<=n;i++){ fibN = fib1 + fib2; fib1 = fib2; fib2 = fibN;}return fibN;}int main(){int n = 10;long res = fibo(n);printf("%d
",res);return 0;}
推薦閱讀: