Can the execution time of this prime number generator be improved?

后端 未结 5 2143
情书的邮戳
情书的邮戳 2020-12-30 09:22

My initial goal when writing this was to leave the smallest footprint possible. I can say with confidence that this goal has been met. Unfortunately, this leaves me with a r

5条回答
  •  悲&欢浪女
    2020-12-30 10:09

    I wrote an imperative version, which is faster. It may be impossible to write Sieve of Eratosthenes in a pure functional way to achieve the same speed since you must have a binary state for each number.

    let generatePrimes max=
        let p = Array.create (max+1) true
        let rec filter i step = 
            if i <= max then 
                p.[i] <- false
                filter (i+step) step
        {2..int (sqrt (float max))} |> Seq.map (fun i->filter (i+i) i) |> Seq.length |> ignore
        {2..max} |> Seq.filter (fun i->p.[i]) |> Seq.toArray
    

提交回复
热议问题