lecture11

lecture11 - COMP 250 Winter 2010 lecture 11 -...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
lecture 11 - decimal-to-binary, power, binary search Jan 29, 2010 Today we will look at three diferent recursive algorithms which have a similar behavior, in that all three are (recursively) called approximately logn times Decimal to binary conversion Recall the algorithm For converting a decimal number n to binary. Note we can write the algorithm recursively. Like with Factorial, the number oF steps needed to to run the algorithm is about the same Algorithm: DecimalToBinary(n) Input: a decimal number n Output: sequence oF bits b i From least ( i = 0) to most signi±cant, representing n in bi- nary if n 1 then print n %2 DecimalToBinary ( n / 2 ) end if For the recursive and non-recursive versions. ²or decimal to binary conversion, it is proportional to log n . ²or Factorial, it was proportional to n . Note, that the number oF recursive calls you need For the above algorithm is (approximately) the number oF bits you need to represent the number n in binary, namely about log 2 n . (I say “about” because log 2 n might not be even, and we need to call the method iF n = 1 even though log 1 = 0. These “of by one” issues are not the main point here, though.) A ±nal note: one student observed in class that iF you switch the order oF the print and recursive call, then you will print the bits in the opposite order, namely From most signi±cant to least signi±cant. (i.e. the ±rst print only occurs aFter you have done all the recursive calls and the parameter n has been reduced to 0. Power ( x n ) Our next example looks very diferent at ±rst glance, but we will see that it is in Fact very similar. Consider an algorithm For computing x raised to some power n . An iterative (non-recursive) method For doing it is: Algorithm: Power(x,n) Input: a real number x and a positive integer n Output: x n result 1 for i = 1 to n do result result * x end for return result Here is an interesting recursive way to compute
Background image of page 1

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

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 09/25/2011 for the course COMP 250 taught by Professor Blanchette during the Spring '08 term at McGill.

Page1 / 4

lecture11 - COMP 250 Winter 2010 lecture 11 -...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online