2019-02-04 Basic Algorithms Lec3

2019-02-05  本文已影响0人  ANPULI

Recursion

Exponentiation Problem

Input

Positive integers: b and n

Output

b^n

Puesdocode

function Exp(b,n)
    result = 1
    for i = i to n
        result = result * b
    return result

Multiplications: n

Goal: Less multiplications

2^{1000} = 2^{500} \times 2^{500}

  1. compute 2^{500}
  2. square it
    2^{500} = 2^{250} \times 2^{250}
    1. compute 2^{250}
    2. square it

Total: 252 multiplications

2^{125} = 2^{62.5} \times 2^{62.5} = 2^{62} \times 2^{62} \times 2

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

c = a^b \Longleftrightarrow log_a{b}
2^k \leq m < 2^{k+1}
number of multiplications \leq 2\times log_2{m} + 4 (worst case)

Binary Search Problem

Input

Output

Puesdocode

T(n) = max number of recursive calls for an array of length n

上一篇下一篇

猜你喜欢

热点阅读