2019-02-04 Basic Algorithms Lec3

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

  1. compute
  2. square it
    1. compute
    2. square it

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 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)