Is the Sieve of Eratosthenes an example of Dynamic Programming?

半腔热情 提交于 2019-12-08 03:53:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!