13-recursive_programming

# 13-recursive_programming - CSE 143 Lecture 13 Recursive...

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

CSE 143 Lecture 13 Recursive Programming reading: 12.2 - 12.3 slides created by Marty Stepp http://www.cs.washington.edu/143/

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

View Full Document
2 Exercise • Write a recursive method pow accepts an integer base and exponent and returns the base raised to that exponent. –Examp le : pow(3, 4)
3 pow solution // Returns base ^ exponent. // Precondition: exponent >= 0 public static int pow(int base, int exponent) { if (exponent == 0) { // base case; any number to 0th power is 1 return 1; } else { // recursive case: x^y = x * x^(y-1) return base * pow(base, exponent - 1); } }

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

View Full Document
4 An optimization • Notice the following mathematical property: 3 12 = 531441 = 9 6 = ( 3 2 ) 6 531441 = ( 9 2 ) 3 = (( 3 2 ) 2 ) 3 – When does this "trick" work? – How can we incorporate this optimization into our pow method? – What is the benefit of this trick if the method already works?
5 pow solution 2 // Returns base ^ exponent. // Precondition: exponent >= 0 public static int pow(int base, int exponent) { if (exponent == 0) { // base case; any number to 0th power is 1 return 1; } else if (exponent % 2 == 0) { // recursive case 1: x^y = (x^2)^(y/2) return pow(base * base, exponent / 2); } else { // recursive case 2: x^y = x * x^(y-1) return base * pow(base, exponent - 1); } }

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

View Full Document
6 Exercise • Write a recursive method printBinary that accepts an integer and prints that number's representation in binary (base 2) . –Examp
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 01/04/2011 for the course CSE 143 taught by Professor Sr during the Spring '08 term at University of Washington.

### Page1 / 16

13-recursive_programming - CSE 143 Lecture 13 Recursive...

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

View Full Document
Ask a homework question - tutors are online