50 likes | 141 Views
遞迴補充說明. int f(int x) { return x + f(x); }. int f(int x) { if(x<1) return 0; else return x + f(x); }. Homework 5. 利用遞迴及非遞迴方式撰寫 Fibonacci 的程式。 User 輸入 n 值,計算出 Fib(n) Fib(n) = Fib(n-1) + Fib(n-2) Fib(0) = 0, Fib(1) = 1 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ….
E N D
遞迴補充說明 int f(int x) { return x + f(x); }
int f(int x) { if(x<1) return 0; else return x + f(x); }
Homework 5 • 利用遞迴及非遞迴方式撰寫Fibonacci的程式。 • User輸入n值,計算出Fib(n) • Fib(n) = Fib(n-1) + Fib(n-2) • Fib(0) = 0, Fib(1) = 1 • 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
Fib(n) = Fib(n-1) + Fib(n-2) • Fib(0) = 0, Fib(1) = 1 • 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … int fib(int n) { if(n<=0) return 0; else if(n==1) return 1; else return fib(n-1)+fib(n-2); }
Fib(n) = Fib(n-1) + Fib(n-2) • Fib(0) = 0, Fib(1) = 1 • 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … int fib(int n) { int sum=0, a=0, b=1; for(int i=0; i<n-1; i++) { sum=a+b; b=sum; a=b; } return sum; } int fib(int n) { if(n<=0) return 0; else if(n==1) return 1; else return fib(n-1)+fib(n-2); }