我阅读了有关该算法的 F# 版本的另一篇文章。我发现它非常优雅,并尝试将答案的一些想法结合起来。
尽管我对其进行了优化以减少检查(仅检查 6 左右的数字)并省略不必要的缓存,但它仍然非常缓慢。计算第 10,000个素数已经花费了 5 多分钟。使用命令式方法,我可以在不多的时间内测试所有 31 位整数。
所以我的问题是我是否遗漏了一些让这一切变得如此缓慢的东西。例如,在另一篇文章中,有人推测LazyList
可能会使用锁定。有人有想法吗?
由于 StackOverflow 的规则说不要发布新问题作为答案,我觉得我必须为此开始一个新话题。
这是代码:
#r "FSharp.PowerPack.dll"
open Microsoft.FSharp.Collections
let squareLimit = System.Int32.MaxValue |> float32 |> sqrt |> int
let around6 = LazyList.unfold (fun (candidate, (plus, next)) ->
if candidate > System.Int32.MaxValue - plus then
None
else
Some(candidate, (candidate + plus, (next, plus)))
) (5, (2, 4))
let (|SeqCons|SeqNil|) s =
if Seq.isEmpty s then SeqNil
else SeqCons(Seq.head s, Seq.skip 1 s)
let rec lazyDifference l1 l2 =
if Seq.isEmpty l2 then l1 else
match l1, l2 with
| LazyList.Cons(x, xs), SeqCons(y, ys) ->
if x < y then
LazyList.consDelayed x (fun () -> lazyDifference xs l2)
elif x = y then
lazyDifference xs ys
else
lazyDifference l1 ys
| _ -> LazyList.empty
let lazyPrimes =
let rec loop = function
| LazyList.Cons(p, xs) as ll ->
if p > squareLimit then
ll
else
let increment = p <<< 1
let square = p * p
let remaining = lazyDifference xs {square..increment..System.Int32.MaxValue}
LazyList.consDelayed p (fun () -> loop remaining)
| _ -> LazyList.empty
loop (LazyList.cons 2 (LazyList.cons 3 around6))