Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion Method calling itself (circular definition)

Similar presentations


Presentation on theme: "Recursion Method calling itself (circular definition)"— Presentation transcript:

1 Recursion Method calling itself (circular definition)
A recurrence formula for evaluation A recurrence terminating condition Is easier and natural to write. Is more ‘expensive’ than iterative computation

2 factorial class fact { public static int factorial(int n){ int fact;
if (n==0) fact = 1; else fact = n * factorial(n-1); return fact; } public static void main (String args[]) { System.out.println(factorial(7));

3 Reverse a string class reversestring {
public static String reverse1(String S){ if (S.length() == 1 ) return S; else return (reverse1(S.substring(1)) + S.charAt(0)); } public static String reverse2(String S){ else return (S.charAt(S.length()-1) + reverse2(S.substring(0,S.length()-1)) ); public static void main(String args[]){ String s = "This is a headline"; System.out.println(s); String r1 = reverse1(s); System.out.println(r1); //String r2 = reverse2(r1); //System.out.println(r2); System.out.println(reverse1(reverse2(s)));

4 GCD revisited Recall that gcd (a, b) = gcd (a-b, b) assuming a > b.
Directly defines a recurrence public static int gcd (int a, int b) { if ((a==1) || (b==1)) return 1; if (a==b) return a; if (a < b) return gcd (a, b-a); if (a > b) return gcd (a-b, b); }

5 GCD revisited Refinement: gcd (a, b) = gcd (a-nb, b) for any positive integer n such that a >= nb, in particular n = a/b, assuming a > b public static int gcd (int a, int b) { if (0==a) return b; if (0==b) return a; if (a < b) return gcd (a, b%a); if (a > b) return gcd (a%b, b); }


Download ppt "Recursion Method calling itself (circular definition)"

Similar presentations


Ads by Google