The sieve of Sundaram

Revision as of 19:48, 8 August 2021 by rosettacode>Gerard Schildberger (added the Prime Number category.)

The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes 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.

The sieve of Sundaram is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

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 Eratosthenes.

References

ALGOL 68

Translation of: Nim

To run this with Algol 68G, you will need to increase the heap size by specifying e.g. -heap=64M on the command line. <lang algol68>BEGIN # sieve of Sundaram #

   INT n = 8 000 000;
   INT none = 0, mark1 = 1, mark2 = 2;
   [ 1 : n ]INT mark;
   FOR i FROM LWB mark TO UPB mark DO mark[ i ] := none  OD;
   FOR i FROM   4 BY 3 TO UPB mark DO mark[ i ] := mark1 OD;
   INT            count := 0; # Count of primes.          #
   [ 1 : 100 ]INT list100;    # First 100 primes.         #
   INT            last  := 0; # Millionth prime.          #
   INT            step  := 5; # Current step for marking. #
   FOR i TO n WHILE last = 0 DO
       IF mark[ i ] = none THEN # Add/count a new odd prime.  #
           count +:= 1;
           IF   count <= 100 THEN
               list100[ count ] := 2 * i + 1
           ELIF count = 1 000 000 THEN
               last := 2 * i + 1
           FI
       ELIF mark[ i ] = mark1 THEN # Mark new numbers using current step. #
           IF i > 4 THEN
               FOR k FROM i + step BY step TO n DO
                   IF mark[ k ] = none THEN mark[ k ] := mark2 FI
               OD;
               step +:= 2
           FI
     # ELSE must be mark2 - Ignore this number. #
       FI
   OD; 
   print( ( "First 100 Sundaram primes:", newline ) );
   FOR i FROM LWB list100 TO UPB list100 DO
       print( ( whole( list100[ i ], -3 ) ) );
       IF i MOD 10 = 0 THEN print( ( newline ) ) ELSE print( ( " " ) ) FI
   OD;
   print( ( newline ) );
   IF last = 0 THEN
       print( ( "Not enough values in sieve. Found only ", whole( count, 0 ), newline ) )
   ELSE
       print( ( "The millionth Sundaram prime is ", whole( last, 0 ), newline ) )
   FI

END</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 Sundaram prime is 15485867

C#

Generating prime numbers during sieve creation gives a performance boost over completing the sieve and then scanning the sieve for output. There are, of course, a few at the end to scan out. <lang csharp>using System; using System.Collections.Generic; using System.Linq; using static System.Console;

class Program {

 static string fmt(int[] a)
 {
   var sb = new System.Text.StringBuilder();
   for (int i = 0; i < a.Length; i++)
     sb.Append(string.Format("{0,5}{1}",
       a[i], i % 10 == 9 ? "\n" : " "));
   return sb.ToString();
 }
 static void Main(string[] args)
 {
   var sw = System.Diagnostics.Stopwatch.StartNew();
   var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray();
   sw.Stop();
   Write("The first 100 odd prime numbers:\n{0}\n",
     fmt(pr.Take(100).ToArray()));
   Write("The millionth odd prime number: {0}", pr.Last());
   Write("\n{0} ms", sw.Elapsed.TotalMilliseconds);
 }

}

class PG {

 public static IEnumerable<int> Sundaram(int n)
 {
   // yield return 2;
   int k = (n + 1) >> 1, v = 1;
   var comps = new bool[k + 1];
   for (int i = 1, j = 3; i < k; i++, j += 2)
   {
     int t = ((i + i * i) << 1) - j;
     for (; v < t; v++)
       if (!comps[v])
         yield return (v << 1) + 1;
     while ((t += j) < k)
       comps[t] = true;
   }
   for (; v < k; v++)
     if (!comps[v])
       yield return (v << 1) + 1;
 }

}</lang>

Output:

Under 1/5 of a second @ Tio.run

The first 100 odd prime numbers:
    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 odd prime number: 15485867
184.3825 ms

P.S. for those (possibly faithless) who wish to have a conventional prime number generator, one can uncomment the yield return 2 line at the top of the function.

F#

<lang fsharp> // The sieve of Sundaram. 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 Sundaram 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 Sundaram prime is 15485867

Nim

<lang Nim>import strutils

const N = 8_000_000

type Mark {.pure.} = enum None, Mark1, Mark2

var mark: array[1..N, Mark] for n in countup(4, N, 3): mark[n] = Mark1


var count = 0 # Count of primes. var list100: seq[int] # First 100 primes. var last = 0 # Millionth prime. var step = 5 # Current step for marking.

for n in 1..N:

 case mark[n]
 of None:
   # Add/count a new odd prime.
   inc count
   if count <= 100:
     list100.add 2 * n + 1
   elif count == 1_000_000:
     last = 2 * n + 1
     break
 of Mark1:
   # Mark new numbers using current step.
   if n > 4:
     for k in countup(n + step, N, step):
       if mark[k] == None: mark[k] = Mark2
     inc step, 2
 of Mark2:
   # Ignore this number.
   discard


echo "First 100 Sundaram primes:" for i, n in list100:

 stdout.write ($n).align(3), if (i + 1) mod 10 == 0: '\n' else: ' '

echo() if last == 0:

 quit "Not enough values in sieve. Found only $#.".format(count), QuitFailure

echo "The millionth Sundaram prime is ", ($last).insertSep()</lang>

Output:
First 100 Sundaram primes:
  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 Sundaram prime is 15_485_867

Wren

Library: Wren-fmt
Library: Wren-seq

I've worked here from the second (optimized) Python example in the Wikipedia article for SOS which allows an easy transition to an 'odds only' SOE for comparison. <lang ecmascript>import "/fmt" for Fmt import "/seq" for Lst

var sos = Fn.new { |n|

   if (n < 3) return []
   var primes = []
   var k = ((n-3)/2).floor + 1
   var marked = List.filled(k, true)
   var limit = ((n.sqrt.floor - 3)/2).floor + 1
   limit = limit.max(0)
   for (i in 0...limit) {
       var p = 2*i + 3
       var s = ((p*p - 3)/2).floor
       var j = s
       while (j < k) {
           marked[j] = false
           j = j + p
       }
   }
   for (i in 0...k) {
       if (marked[i]) primes.add(2*i + 3)
   }
   return primes

}

// odds only var soe = Fn.new { |n|

   if (n < 3) return []
   var primes = []
   var k = ((n-3)/2).floor + 1
   var marked = List.filled(k, true)
   var limit = ((n.sqrt.floor - 3)/2).floor + 1
   limit = limit.max(0)
   for (i in 0...limit) {
       if (marked[i]) {
           var p = 2*i + 3
           var s = ((p*p - 3)/2).floor
           var j = s
           while (j < k) {
               marked[j] = false
               j = j + p
           }
       }
   }
   for (i in 0...k) {
       if (marked[i]) primes.add(2*i + 3)
   }
   return primes

}

var limit = 16e6 // say var start = System.clock var primes = sos.call(limit) var elapsed = ((System.clock - start) * 1000).round Fmt.print("Using the Sieve of Sundaram generated primes up to $,d in $,d ms.\n", limit, elapsed) System.print("First 100 odd primes generated by the Sieve of Sundaram:") for (chunk in Lst.chunks(primes[0..99], 10)) Fmt.print("$3d", chunk) Fmt.print("\nThe $,d Sundaram prime is $,d", 1e6, primes[1e6-1])

start = System.clock primes = soe.call(limit) elapsed = ((System.clock - start) * 1000).round Fmt.print("\nUsing the Sieve of Eratosthenes would have generated them in $,d ms.", elapsed) Fmt.print("\nAs a check, the $,d Sundaram prime would again have been $,d", 1e6, primes[1e6-1])</lang>

Output:
Using the Sieve of Sundaram generated primes up to 16,000,000 in 1,232 ms.

First 100 odd primes generated by the Sieve of Sundaram:
  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 1,000,000 Sundaram prime is 15,485,867

Using the Sieve of Eratosthenes would have generated them in 797 ms.

As a check, the 1,000,000 Sundaram prime would again have been 15,485,867