美文网首页
2019-02-04 Basic Algorithms Lec3

2019-02-04 Basic Algorithms Lec3

作者: ANPULI | 来源:发表于2019-02-05 02:26 被阅读0次

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

  • sorted array A of numbers
  • number X

Output

  • i such that A[i] = x
  • -1 if such i does not exist

Puesdocode

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

相关文章

网友评论

      本文标题:2019-02-04 Basic Algorithms Lec3

      本文链接:https://www.haomeiwen.com/subject/weumsqtx.html