23recursion

# 23recursion - Overview 2.3 Recursion What is recursion When...

This preview shows pages 1–4. Sign up to view the full content.

2.3 Recursion Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · September 28, 2008 11:25 AM 2 Overview What is recursion? When one function calls itself directly or indirectly. Why learn recursion? ! New mode of thinking. ! Powerful programming paradigm. Many computations are naturally self-referential. ! Mergesort, FFT, gcd. ! Linked data structures. ! A folder contains files and other folders. Closely related to mathematical induction. Reproductive Parts M. C. Escher, 1948 3 Greatest Common Divisor Gcd. Find largest integer that evenly divides into p and q. Ex. gcd(4032, 1272) = 24. Applications. ! Simplify fractions: 1272/4032 = 53/168. ! RSA cryptosystem. 4032 = 2 6 ! 3 2 ! 7 1 1272 = 2 3 ! 3 1 ! 53 1 gcd = 2 3 ! 3 1 = 24 4 Greatest Common Divisor Gcd. Find largest integer that evenly divides into p and q. Euclid's algorithm. [Euclid 300 BCE] gcd(4032, 1272) = gcd(1272, 216) = gcd(216, 192) = gcd(192, 24) = gcd(24, 0) = 24. gcd( p , q ) = p if q = 0 gcd( q , p % q ) otherwise " # \$ base case reduction step, converges to base case 4032 = 3 ! 1272 + 216

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
5 Greatest Common Divisor Gcd. Find largest integer d that evenly divides into p and q. p p % q x x x x x x x x p = 8x q = 3x gcd(p, q) = x gcd gcd( p , q ) = p if q = 0 gcd( q , p % q ) otherwise " # \$ base case reduction step, converges to base case 6 Greatest Common Divisor Gcd. Find largest integer d that evenly divides into p and q. Java implementation. base case reduction step public static int gcd ( int p , int q ) { if ( q == 0 ) return p ; else return gcd ( q , p % q ); } gcd( p , q ) = p if q = 0 gcd( q , p % q ) otherwise " # \$ base case reduction step, converges to base case Recursive Graphics 9
10 Htree H-tree of order n.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 12/16/2008 for the course COS 126 taught by Professor Douglasw.clark during the Fall '08 term at Princeton.

### Page1 / 7

23recursion - Overview 2.3 Recursion What is recursion When...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online