lecture 11  decimaltobinary, 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 nonrecursive 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 (nonrecursive) 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
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.
 Spring '08
 BLANCHETTE
 Computer Science, Algorithms, Binary Search, Binary numeral system, Decimal, multiplications

Click to edit the document details