The sieve of Sundaram
The sieve of Erastothenes: you've been there; done that; have the T-shirt. The sieve of Erastothenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Erastothenes.
F#
<lang fsharp> // The sieve of Sudaram. Nigel Galloway: August 7th., 2021 let sPrimes()=
let sSieve=System.Collections.Generic.Dictionary<int,(unit -> int) list>() let rec fN g=match g with h::t->(let n=h() in if sSieve.ContainsKey n then sSieve.[n]<-h::sSieve.[n] else sSieve.Add(n,[h])); fN t|_->() let fI n=if sSieve.ContainsKey n then fN sSieve.[n]; sSieve.Remove n|>ignore; None else Some(2*n+1) let fG n g=let mutable n=n in (fun()->n<-n+g; n) let fE n g=if not(sSieve.ContainsKey n) then sSieve.Add(n,[fG n g]) else sSieve.[n]<-(fG n g)::sSieve.[g] let fL =let mutable n,g=4,3 in (fun()->n<-n+3; g<-g+2; fE (n+g) g; n) sSieve.Add(4,[fL]); Seq.initInfinite((+)1)|>Seq.choose fI
sPrimes()|>Seq.take 100|>Seq.iter(printf "%d "); printfn "" printfn "The millionth Sudaram prime is %d" (Seq.item 999999 (sPrimes())) </lang>
- Output:
3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 The millionth Sudaram prime is 15485867