How to resolve the algorithm Sieve of Pritchard step by step in the C# programming language
How to resolve the algorithm Sieve of Pritchard step by step in the C# programming language
Table of Contents
Problem Statement
The Sieve of Pritchard is an algorithm for finding the prime numbers up to a given limit N, published in 1981. It considers many fewer composite numbers than the Sieve of Eratosthenes (and has a better asymptotic time complexity). However, unlike the latter, it cannot be modified to greatly reduce its space requirement, making it unsuitable for very large limits. Conceptually, it works by building a wheel representing the repeating pattern of numbers not divisible by one of the first k primes, increasing k until the square of the k'th prime is at least N. Since wheels grow very quickly, the algorithm restricts attention to the initial portions of wheels up to N. (Small examples of the wheels constructed by the Sieve of Pritchard are used in the "wheel-based optimizations" mentioned in the Eratosthenes task.) For example, the second-order wheel has circumference 6 (the product of the first two primes, 2 and 3) and is marked only at the numbers between 1 and 6 that are not multiples of 2 or 3, namely 1 and 5. As this wheel is rolled along the number line, it will pick up only numbers of the form 6k+1 or 6k+5 (that is, n where n mod 6 is in {1,5}). By the time it stops at 30 (2x3x5) it has added only 8 of the numbers between 6 and 30 as candidates for primality. Those that are multiples of 5 (only 2: 15 and 55) are obtained by multiplying the members of the second-order wheel. Removing them gives the next wheel, and so on. This YouTube video presents the execution of the algorithm for N=150 in a format that permits single-stepping forward and backward through the run. In that implementation, the wheel is represented by a sparse global array s such that for each member w of the wheel, s[w] contains the next member of the wheel; along with a similar "previous member" value, this allows numbers to be removed in a constant number of operations. But the simple abstract algorithm is based on an ordered set, and there is plenty of scope for different implementations. Write a program/subprogram that uses the Sieve of Pritchard algorithm to find all primes up to a specified limit. Show the result of running it with a limit of 150.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sieve of Pritchard step by step in the C# programming language
The provided C# code implements the Pritchard's Wheel Factorization algorithm to generate prime numbers up to a specified limit. Here's an explanation of what the code does:
-
Function PrimesUpTo: This function takes an integer
limit
as its argument and returns a list of prime numbers up to that limit. It also accepts an optional booleanverbose
argument, which controls whether the function prints information about the process. -
Algorithm: The algorithm used is the Pritchard's Wheel Factorization, an optimized version of the Sieve of Eratosthenes. It works by maintaining two sets:
- Members: A sorted set that initially contains the number 1.
- Primes: A list to store the identified prime numbers.
-
Initialization: The algorithm starts by initializing the variables:
stp
(step) is set to 1.prime
is set to 2, which is the first prime number.n
is used to iterate through numbers.nxtpr
is used to find the next prime to remove.rtlim
is the square root oflimit
, up to which the algorithm searches for primes.nl
is the current limit for removing non-prime numbers.
-
Wheel Generation: The algorithm creates a wheel of multiples for the prime
prime
by iterating through the members of theMembers
set and adding multiples ofprime
to theMembers
set. This wheel helps identify non-prime numbers efficiently. -
Marking Non-Primes: The algorithm marks all non-prime numbers by removing them from the
Members
set. This is done by iterating through the members of theMembers
set and removing any number that is a multiple of the current primeprime
. -
Updating and Iterating: The algorithm updates
stp
to the current value ofnl
and incrementsprime
to the next prime number. It repeats this process untilprime
is greater than or equal to the square root oflimit
. -
Adding Primes: The primes are added to the
Primes
list as they are identified. -
Post-Processing: After the wheel approach, the remaining numbers in the
Members
set (except for 1) are prime numbers, so they are added to thePrimes
list. -
Output: If
verbose
is true, the function prints information about the process, including the number of primes found and the total time taken. -
Main Function: The
Main
function callsPrimesUpTo
to generate and print prime numbers up to 150 and 1,000,000.
Source code in the csharp programming language
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, bool verbose = false) {
var sw = System.Diagnostics.Stopwatch.StartNew();
var members = new SortedSet<int>{ 1 };
int stp = 1, prime = 2, n, nxtpr, rtlim = 1 + (int)Math.Sqrt(limit), nl, ac = 2, rc = 1;
List<int> primes = new List<int>(), tl = new List<int>();
while (prime < rtlim) {
nl = Math.Min(prime * stp, limit);
if (stp < limit) {
tl.Clear();
foreach (var w in members)
for (n = w + stp; n <= nl; n += stp) tl.Add(n);
members.UnionWith(tl); ac += tl.Count;
}
stp = nl; // update wheel size to wheel limit
nxtpr = 5; // for obtaining the next prime
tl.Clear();
foreach (var w in members) {
if (nxtpr == 5 && w > prime) nxtpr = w;
if ((n = prime * w) > nl) break; else tl.Add(n);
}
foreach (var itm in tl) members.Remove(itm); rc += tl.Count;
primes.Add(prime);
prime = prime == 2 ? 3 : nxtpr;
}
members.Remove(1); primes.AddRange(members); sw.Stop();
if (verbose) Console.WriteLine("Up to {0}, added:{1}, removed:{2}, primes counted:{3}, time:{4} ms", limit, ac, rc, primes.Count, sw.Elapsed.TotalMilliseconds);
return primes;
}
static void Main(string[] args) {
Console.WriteLine("[{0}]", string.Join(", ", PrimesUpTo(150, true)));
PrimesUpTo(1000000, true);
}
}
You may also check:How to resolve the algorithm Break OO privacy step by step in the Raku programming language
You may also check:How to resolve the algorithm Pinstripe/Display step by step in the Locomotive Basic programming language
You may also check:How to resolve the algorithm Pig the dice game step by step in the Python programming language
You may also check:How to resolve the algorithm Loops/Nested step by step in the Elixir programming language
You may also check:How to resolve the algorithm Write language name in 3D ASCII step by step in the COBOL programming language