Sieve of Pritchard: Difference between revisions

Content added Content deleted
m (→‎{{header|Python}}: a set() can .add, but not .append() - problem only shows up for smaller limtits such as 40)
(Added C# version, loosely translated from python version)
Line 25: Line 25:
*   [[partition an integer X into N primes]]
*   [[partition an integer X into N primes]]
*   [[sequence of primes by Trial Division]]
*   [[sequence of primes by Trial Division]]


=={{header|C#|CSharp}}==
Loosely based on the Python version. I cut a couple of things out and it still worked. Not too crazy about having to create temporary lists to add or remove from the HashSet, seems inefficient. But that is the work-around I employed, since HashSets can't be accessed by indexing. I haven't yet directly tested this against a Sieve of Eratosthenes to compare performance.
<syntaxhighlight lang=csharp>using System;
using System.Collections.Generic;

class Program {

// Returns list of primes up to limit using Pritchard (wheel) sieve
static List<int> PrimesUpTo(int limit) {
var members = new HashSet<int>{ 1 };
int stp = 1, prime = 2, n, np, rtlim = 1 + (int)Math.Sqrt(limit);
var primes = new List<int>();
while (prime <= rtlim) {
if (stp < limit)
foreach (var w in new List<int>(members)) {
n = w + stp;
while (n <= limit) { members.Add(n); n += stp; }
}
stp = Math.Min(prime * stp, limit);
np = 0;
foreach (var w in new List<int>(members)) {
if (np == 0 && w > prime) np = w; // next prime
if (members.Contains(n = prime * w)) members.Remove(n);
}
primes.Add(prime);
prime = prime == 2 ? 3 : np;
}
members.Remove(1);
primes.AddRange(members);
return primes;
}

static void Main(string[] args) {
Console.WriteLine("[" + string.Join(", ", PrimesUpTo(150)) + "]");
}
}</syntaxhighlight>
{{out}}
<pre>[2, 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]</pre>


=={{header|J}}==
=={{header|J}}==