100 likes | 197 Views
遞迴. 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);
E N D
遞迴 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); 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
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); • }
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); }
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
費式系列 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"); }
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]; }
static int fib_recursive(int n) { if (n<=2) return 1; else return (fib_recursive(n-1)+fib_recursive(n-2)); }
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,....