Академический Документы
Профессиональный Документы
Культура Документы
Announcements
Time
def factors(n):
Slow: Test each k from 1 through n
(Demo)
4
Space
Active environments:
Environments for any function calls currently being evaluated
Parent environments of functions named in active environments
(Demo)
Interactive Diagram
fib(3)
fib(1)
1
fib(4)
fib(2)
fib(0)
fib(1)
fib(2)
fib(3)
fib(0)
fib(1)
fib(1)
Assume we have
reached this step
fib(2)
fib(0)
fib(1)
Can be reclaimed
Hasn't yet been created
fib(3)
fib(1)
1
fib(4)
fib(2)
fib(0)
fib(1)
fib(2)
fib(3)
fib(0)
fib(1)
fib(1)
Assume we have
reached this step
fib(2)
fib(0)
fib(1)
Order of Growth
Order of Growth
A method for bounding the resources used by a function by the "size" of a problem
n:
R(n):
R(n) =
(f (n))
k1 f (n)
R(n)
k2 f (n)
Counting Factors
p
1 and
n
p
1)
def factors_fast(n):
sqrt_n = sqrt(n)
k, total = 1, 0
while k < sqrt_n:
if divides(k, n):
total += 2
k += 1
if k * k == n:
total += 1
return total
def factors(n):
Slow: Test each k from 1 through n
Fast: Test each k from 1 to square root n
For every k, n/k is also a factor!
Time
(n)
p
( n)
Space
(1)
(1)
Assumption:
integers occupy a
fixed amount of
space
12
Exponentiation
Exponentiation
Goal: one more multiplication lets us double the problem size
def exp(b, n):
if n == 0:
return 1
else:
return b * exp(b, n-1)
bn =
1
b bn
bn =
1
1
(b 2 n )2
b bn 1
if n = 0
otherwise
def square(x):
return x*x
def exp_fast(b, n):
if n == 0:
return 1
elif n % 2 == 0:
return square(exp_fast(b, n//2))
else:
return b * exp_fast(b, n-1)
if n = 0
if n is even
if n is odd
(Demo)
14
Exponentiation
Goal: one more multiplication lets us double the problem size
Time
def exp(b, n):
if n == 0:
return 1
else:
return b * exp(b, n-1)
Space
(n)
(n)
(log n)
(log n)
def square(x):
return x*x
def exp_fast(b, n):
if n == 0:
return 1
elif n % 2 == 0:
return square(exp_fast(b, n//2))
else:
return b * exp_fast(b, n-1)
15
(500 n)
(n)
1
n)
500
Logarithms: The base of a logarithm does not affect the order of growth of a process
(log10 n)
(log2 n)
(ln n)
Nesting: When an inner process is repeated for each step in an outer process, multiply the
steps in the outer and inner processes to find the total number of steps
def overlap(a, b):
count = 0
for item in a:
if item in b:
count += 1
return count
Outer: length of a
Inner: length of b
Lower-order terms: The fastest-growing part of the computation dominates the total
(n2 )
(n2 + n)
Exponential growth.
steps, where
1+ 5
2
1.61828
(n2 )
Quadratic growth.
E.g., overlap
(n)
Linear growth.
p
( n)
(log n)
E.g., factors_fast
(1)