13-recursive_programming

# 13-recursive_programming - CSE143 Lecture13...

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. Example:  pow(3, 4)  returns 81 Solve the problem recursively and without using loops.
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?
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) .
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 16

13-recursive_programming - CSE143 Lecture13...

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

View Full Document
Ask a homework question - tutors are online