1 / 10

Lai Ah Fur

遞迴. Lai Ah Fur. Recursion. Recursive program: call by itself 會無窮迴圈 , 故需設定終止條件 (ground case) Solve the complex problems 費耗用 System Stack. 0 if n=0 (anchor or ground base) n+S(n-1) if n>0 (inductive). S(n)=. result=sum(n);

Download Presentation

Lai Ah Fur

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. 遞迴 Lai Ah Fur

  2. Recursion • Recursive program: call by itself • 會無窮迴圈,故需設定終止條件(ground case) • Solve the complex problems • 費耗用System Stack

  3. 0 if n=0 (anchor or ground base) n+S(n-1) if n>0 (inductive) S(n)= result=sum(n); System.out.println("1+2+3+...+"+n+"="+result); static int sum(int n) { if (n==0) return 0; else return (n+sum(n-1)); } //sum

  4. GCD輾轉相減法 • static int gcd_loop1(int m, int n)   • {   • while (m!=n)   • {   • while (m>n) m=m-n;   • while (m<n) n=n-m;   • }   • return (m);   • }  

  5. GCD輾轉相除法 static int gcd_loop2(int m, int n)   {   int t;   if (m<n)   { t=m;m=n;n=t; }   while (n!=0)   {   t=m%n; m=n; n=t;   }   return (m);   }  

  6. Recursive GCD static int gcd(int m, int n)   {   int temp;   if (m<n) {temp=m;m=n;n=temp;}   if (m%n==0) return (n);   else return (gcd(n,m%n));   }//gcd  

  7. 費式系列 static void fib_nonarray(int n) { int first=1,second=1,next=0; first=second=1; System.out.print(first +" "+second+" "); for(int i=3;i<=n;i++) { next=first+second; System.out.print(next+" "); second=first; first=next; }//for System.out.println("\n"); }

  8. static void fib_nonrecursive(int n) { fib[1]=fib[2]=1; for(int i=3;i<=n;i++) fib[i]=fib[i-1]+fib[i-2]; }

  9. static int fib_recursive(int n) { if (n<=2) return 1; else return (fib_recursive(n-1)+fib_recursive(n-2)); }

  10. f(n)=1………………...n=1,2 f(n)=f(n-1)+f(n-2)….....n>2 Examples: 1,1,2,3,5,8,13,21,34,35,....

More Related