1 / 5

遞迴補充說明

遞迴補充說明. 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, ….

Download Presentation

遞迴補充說明

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 遞迴補充說明 int f(int x) { return x + f(x); }

  2. int f(int x) { if(x<1) return 0; else return x + f(x); }

  3. 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, …

  4. 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); }

  5. 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); }

More Related