在Go语言中实现一个更好的并发素数筛选算法

huangapple go评论107阅读模式
英文:

A better concurrent prime number sieve in go

问题

在查看了素数筛选代码并了解了并发结构的工作原理后,我发现它非常优雅。然而,它也非常低效,并且据我所知,等同于通过将m除以小于m的每个数字来测试m的可除性的O(n^2)操作。我想我可以修改它,使用将m除以小于或等于sqrt(m)的每个数字来检查m的可除性的O(n^1.5)操作。然而,这比我预期的要困难得多。

我知道这更像是一个算法问题,但它也与并发性非常相关。如何实现O(n^1.5)版本的算法?

英文:

After looking at the prime number sieve code, and seeing how the
concurrent structure works, I found it to be extremely elegant.
However, it's also extremely inefficient, and IIRC, equivalent to the
O(n^2) operation of testing the divisibility of the number m by
dividing it by every number less than m. I figure that I could instead
modify it to use the O(n^1.5) operation of checking the divisibility
of m by dividing it by every number less than or equal to the sqrt(m).
However, this turned out to be a lot harder than I anticipated.

I know this is more of an algorithmics question, but it's also one
extremely relevant to concurrency. How would one implement the
O(n^1.5) version of the algorithm?

答案1

得分: 3

一个可以查找的地方是stackoverflow,例如,问题Concurrent Prime Generator。在答案中,有一个使用Go和通道的答案。

英文:

One place to look is stackoverflow, for example, the question Concurrent Prime Generator. Amongst the answers is one that uses Go and channels.

答案2

得分: 1

优雅但效率低下的素数筛实现已经为函数式编程社区所熟知。Melissa O'Neill的这篇论文提供了关于惰性“流”素数筛的概述,并介绍了高效的替代方法。(该论文使用Haskell编写,但无论如何都值得一读)

英文:

Elegant but inefficient prime sieve implementations are already well known to the Functional Programming community. This paper by Melissa O’Neill gives a good overview of lazy "stream" prime sieves as well as presenting efficient alternatives. (It uses Haskell, but should be a good read anyway)

答案3

得分: 1

埃拉托斯特尼筛法在第i次迭代中确定素数p_i,并在后续迭代中剪除所有p_i的倍数。鉴于此,您唯一可以并行化的操作是剪除操作。这只能通过一个常数因子加快速度,因此您不会改变算法的大O表示方式。

英文:

Eratosthenes' sieve identifies prime p_i at iteration i and prunes all multiples of p_i from consideration in successive iterations. Given that, the only thing you can parallelise here is the pruning operation. This can only be sped up by a constant factor, so you won't change the big-O of the algorithm this way.

huangapple
  • 本文由 发表于 2011年2月6日 23:31:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/4914204.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定