Ever been tasked to come up with lists of prime numbers and you want to use the
Sieve of Eratosthenes[
^] to do so, but aren't quite sure how to code it up in C#? If so, then this simple console program written with .NET should do the trick:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace PrimeFinder
{
class Program
{
static void Main(string[] args)
{
try
{
List<string> outputLines = new List<string>();
string[] numbersList = File.ReadAllLines(args[0]);
foreach(string number in numbersList) {
int N = Int32.Parse(number);
List<int> primeCandidates = new List<int>(N);
if (N==2)
{
outputLines.Add("2\r\n");
continue;
}
if (N==1)
{
throw new InvalidArgumentException("The number one is trivially prime.");
}
primeCandidates.Add(2);
for (int i = 2; i <= (N+1)/2; i++)
primeCandidates.Add(2*i-1);
for(int j = 0;j < primeCandidates.Count;++j) {
int prime = primeCandidates[j];
for( int multiple = 2;multiple*prime <= N;++multiple) {
if (prime == 2) break;
if ((multiple * prime) % 2 == 0)
continue;
if (!primeCandidates.Contains(multiple * prime))
continue;
primeCandidates.Remove(multiple * prime);
}
}
string currentOutputLine = string.Empty;
foreach (int value in primeCandidates)
currentOutputLine += value.ToString() + ',';
currentOutputLine =
currentOutputLine.Remove(currentOutputLine.Length - 1);
currentOutputLine += "\r\n";
Console.Write(currentOutputLine);
outputLines.Add(currentOutputLine);
}
File.WriteAllLines(args[1], outputLines);
Console.WriteLine("DONE computing primes");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
}
}
Brian C. Hart, Ph.D., is a strategic engagement leader on a mission to leverage space technology to protect U.S. interests and assets against adversaries. Throughout Dr. Hart's career, he has enjoyed: Working closely with business executives to provide strategic direction and leadership, translating customer and competitive intelligence into compelling capture strategies and solutions, and mentoring teams to enhance individual and company capabilities while fostering an engaging and accountable environment, being involved in STEAM initiatives and education to develop greater awareness in the community, and serving the armed forces with the U.S. Navy and U.S. Army National Guard. He is excited to begin developing his career in Jacobs's Critical Mission Systems business unit, supporting NORAD and the U.S. Space Force.