Skip to content

Instantly share code, notes, and snippets.

@sholev
Last active March 19, 2016 14:40
Show Gist options
  • Save sholev/1a0125524295e96e08a7 to your computer and use it in GitHub Desktop.
Save sholev/1a0125524295e96e08a7 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
public class SieveOfEratosthenes
{
public static void Main()
{
var n = int.Parse(Console.ReadLine());
bool[] primes = new bool[n + 1];
for (int i = 0; i <= n; i++)
{
primes[i] = true;
}
primes[0] = primes[1] = false;
for (int p = 2; p <= n; p++)
{
if (primes[p])
{
FillPrimes(primes, p);
}
}
DrawTable(primes);
}
private static void FillPrimes(bool[] primes, int step)
{
for (int i = 2 * step; i < primes.Length; i += step)
{
primes[i] = false;
Console.Clear();
//DrawTable(primes);
//Thread.Sleep(200);
}
}
private static void DrawTable(bool[] primes)
{
//StringBuilder output = new StringBuilder();
int tableBoxes = Math.Min(primes.Length / 10, 20);
int numberCount = primes.Length.ToString().Length;
int rowLength = (tableBoxes * numberCount) + (tableBoxes + 1);
Console.WriteLine(new string('_', rowLength));
Console.Write("|");
for (int i = 1; i < primes.Length; i++)
{
if (primes[i])
{
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Black;
Console.Write("{0," + numberCount + "}", i);
}
else
{
Console.BackgroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.White;
Console.Write("{0," + numberCount + "}", " ");
}
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White;
Console.Write("|");
if (i % tableBoxes == 0)
{
Console.WriteLine();
Console.Write(new string('-', (tableBoxes * numberCount) + (tableBoxes + 1)));
Console.WriteLine();
Console.Write("|");
}
}
////Console.WriteLine(output.ToString());
////var result = primes.Select((value, index) => new { index, value })
//// .ToDictionary(pair => pair.index, pair => pair.value)
//// .Where(e => e.Value)
//// .Select(pair => pair.Key);
var result = new List<int>();
for (int i = 0; i < primes.Length; i++)
{
if (primes[i])
{
result.Add(i);
}
}
Console.WriteLine("Primes: {0}", string.Join(", ", result));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment