Recursion
Exponentiation Problem
Input
Positive integers: b
and n
Output
Puesdocode
function Exp(b,n)
result = 1
for i = i to n
result = result * b
return result
Multiplications: n
Goal: Less multiplications
- compute
- square it
- compute
- square it
- compute
Total: 252 multiplications
Puesdocode: Refined Algorithm
function Exp(b, n)
if n = 0
return 1
if n is even
return Exp(b, n/2)^2
else
return Exp(b, (n-1)/2)^2 * b
How many recursive calls are made if n = 2^k
?
k+1
or k+2
?
Logarithms
number of multiplications (worst case)
Binary Search Problem
Input
- sorted array
A
of numbers - number
X
Output
-
i
such thatA[i] = x
-
-1
if suchi
does not exist
Puesdocode
T(n) = max number of recursive calls for an array of length n
网友评论