问题
I'm a bit confused as to whether the Sieve of Eratosthenes (implemented with an array for all the numbers and a loop marking the composite numbers) is an example of Dynamic Programming? A couple of friends were telling me the way it's implemented is an example of Bottom Up DP, but I'm having trouble seeing it. Exactly what are the subproblems and how would you implement SoE with Top-Down / Recursion? Thanks guys.
回答1:
Sure, we could think of the Sieve of Eratosthenes as an example of dynamic programming. The subproblems would be all the composite numbers. Skipping over marked numbers is a perfect demonstration of the subproblems overlapping since if they did not overlap we wouldn't be skipping over them :)
One way we could formulate the sieve recursively could be: let f(N)
represent the N
th prime and its associated sieve state. Then:
f(1) = (2, [4,6...])
f(N) = (q, join( Sieve, [q+q,q+q+q...]))
'''a pair, of the next number q above p
_not_ in Sieve, and the Sieve with
all the multiples of this number q
added into it (we'll place an upper
bound on this process, practically)'''
where (p, Sieve) = f(N - 1)
q = next_not_in(p, Sieve)
Let's test:
f(3) =
call f(2) =
call f(1) =
<-- return (2, [4,6...])
<-- return (3, [4,6,8,9...])
<-- return (5, [4,6,8,9,10...])
来源:https://stackoverflow.com/questions/49026527/is-the-sieve-of-eratosthenes-an-example-of-dynamic-programming