Ch4 Slides
Ch4 Slides
Logarithmic Loops
Learning objective:
to introduce algorithms that perform logarithmic number
of iterations
Lecture Plan:
4.1 Exponents and Logarithms
4.2 Typical algorithms
4.3 Example
4.1 Exponents and Logarithms
Logarithm:
Logarithm to the base 2 of a number x is the power
to which 2 must be raised in order to produce x.
Loops:
- control variable is doubled
or
- control variable is halved
i 1 i n
while i < n do while i > 1 do
application code application code
i i*2 i i/2
The algorithm stops when condition i<n The algorithm stops when condition i>1
is no longer satisfied. This happens when is no longer satisfied. This happens when
at iteration k variable i reaches n=2k. at iteration k variable i reaches n/2k =1.
i 1 i n
while i < n do while i > 1 do
application code application code
i i*2 i i/2
The algorithm stops when condition i<n The algorithm stops when condition i>1
is no longer satisfied. This happens after is no longer satisfied. This happens after
iteration k when i reaches 2k, 2k ≥ n. iteration k when i reaches n/2k, n/2k ≤1.
4.3 Example
Output: 𝑘 + 1
4.3 Example
Output: 𝑘 + 1 = 4
n = ak2k + ak-12k-1+ … + a12+ a0, where ak=1
ALGORITHM number-of-binary-digits(n)
//Input: A positive decimal integer n
//Output: The number of binary digits in the
// binary representation of n
count 1
while n > 1 do
count count+1
n n/2
return count
n n
Iteration (at the start of count (at the end of
iteration) iteration)
1
Tracing for n=13: 1 13 2 6
2 6 3 3
3 3 4 1
4 1
n = ak2k + ak-12k-1+ … + a12+ a0, where ak=1
ALGORITHM number-of-binary-digits(n)
//Input: A positive decimal integer n
//Output: The number of binary digits in the
// binary representation of n
count 1
while n > 1 do
count count+1
n n/2
/
return count
As we have seen, if the control variable is halved, then the number of iterations is
k=log2n.
In the current example, the control variable is halved and rounded down: n n/2 .
This implies that the number of iterations is bounded by k=log2n.
ALGORITHM number-of-binary-digits(n)
//Input: A positive decimal integer n
//Output: The number of binary digits in the
// binary representation of n
count 1
while n > 1 do
count count+1
+
n n/2
/
return count
As we have seen, if the control variable is halved, then the number of iterations is
k=log2n.
In the current example, the control variable is halved and rounded down: n n/2 .
This implies that the number of iterations is bounded by k=log2n.
ALGORITHM number-of-binary-digits(n)
count 1
while n > 1 do
count count+1
n n/2
return count