- 90 Views
- Uploaded on

Download Presentation
## PowerPoint Slideshow about ' Class 4 - Recursion' - mason-hayden

**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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript

Class 4 - Recursion

- More examples of recursion
- Methods with multiple arguments

Thinking recursively

Key ideas:

- Know exactly what the method is supposed to do.
- Assume method works for smaller values. Then just figure out how to use it to compute method for larger values.
- Don’t forget base cases - small values that can be calculated directly.

Example

Given n, print numbers 0, ..., n-1, n.

Example

Given n, calculate n!, defined to be the nth number in the list 1, 1, 2, 6, 24, 120, … (counting from zero)

Example

Given n>=0, print a triangle out of asterisks.

> java triangle

Input number: 4

****

***

**

*

Example

Given integers m, n >= 0, compute mn

Example

Given integers m, n >= 0, compute mn more quickly, using this idea:

mn = 1, if n=0

(mn/2)2, if n even

mmn-1, if n odd

Why more efficient?

Count multiplications:

- pow(m,n): n-1 multiplications
- fastpow(m,n): log2n multiplications

One advantage of recursion is that it sometimes

suggests much more efficient algorithms.

n

(

)

Binomial coefficients(“m choose n”) = number of ways of selecting n items from m>=n objects (disregarding order).

E.g.

4

2

(

)

= 6:

n’

m

n

(

(

)

)

Binomial coefficients (cont.)Assume we can calculate for m’ <= m and/or n’ <= n. How does this help us calculate ?

Select element e out of the m elements. To choose the n elements, either:

- Include e: choose n-1 out of remaining m-1 objects; or
- Exclude e: choose n out of remaining m-1 objects.

n

m-1

n-1

m

0

0

n

m-1

n

(

(

(

(

(

)

)

)

)

)

Binomial coefficients (cont.)Thus, binomial coefficient can be calculated recursively:

= +

Base cases:

= 1

= 0

Download Presentation

Connecting to Server..