The sieve of Sundaram: Difference between revisions

Added C# version
(Added Algol 68)
(Added C# version)
Line 84:
The millionth Sundaram prime is 15485867
</pre>
 
=={{header|C#|CSharp}}==
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)
{
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>
{{out}}
Under 1/5 of a second @ Tio.run
<pre>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</pre>
 
=={{header|F_Sharp|F#}}==