When Generating Primes in F#, why is the “Sieve of Erosthenes” so slow in this particular implementatIon?

后端 未结 4 1581
慢半拍i
慢半拍i 2020-12-11 09:29

IE,

What am I doing wrong here? Does it have to to with lists, sequences and arrays and the way the limitations work?

So here is the setup: I\'m trying to g

4条回答
  •  误落风尘
    2020-12-11 10:02

    Based on my code here: stackoverflow.com/a/8371684/124259

    Gets the first 1 million primes in 22 milliseconds in fsi - a significant part is probably compiling the code at this point.

    #time "on"
    
    let limit = 1000000
    //returns an array of all the primes up to limit
    let table =
        let table = Array.create limit true //use bools in the table to save on memory
        let tlimit = int (sqrt (float limit)) //max test no for table, ints should be fine
        let mutable curfactor = 1;
        while curfactor < tlimit-2 do
            curfactor <- curfactor+2
            if table.[curfactor]  then //simple optimisation
                let mutable v = curfactor*2
                while v < limit do
                    table.[v] <- false
                    v <- v + curfactor
        let out = Array.create (100000) 0 //this needs to be greater than pi(limit)
        let mutable idx = 1
        out.[0]<-2
        let mutable curx=1
        while curx < limit-2 do
            curx <- curx + 2
            if table.[curx] then
                out.[idx]<-curx
                idx <- idx+1
        out
    

提交回复
热议问题