diff --git a/algorithms/CSharp/README.md b/algorithms/CSharp/README.md index 387c6edd..ef07a000 100644 --- a/algorithms/CSharp/README.md +++ b/algorithms/CSharp/README.md @@ -6,6 +6,7 @@ For running the `.cs` file please using [.Net Finddle](https://dotnetfiddle.net/ ## Number Theory 1. [Big Mod Algorithm](src/Number-Theory/big-mod.cs) +2. [Sieve of Eratosthenes](src/Number-Theory/sieve-of-eratosthenes.cs) ## Sorts diff --git a/algorithms/CSharp/src/Number-Theory/sieve-of-eratosthenes.cs b/algorithms/CSharp/src/Number-Theory/sieve-of-eratosthenes.cs new file mode 100644 index 00000000..9c4877fc --- /dev/null +++ b/algorithms/CSharp/src/Number-Theory/sieve-of-eratosthenes.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Algorithms.NumberTheory +{ + public class SieveOfEratosthenes + { + // returns all the prime numbers from 1 to max + public static List PrimeGenerator(int max) + { + List isPrime = Enumerable.Repeat(true, max + 1).ToList(); + + isPrime[0] = isPrime[1] = false; + for(int i = 4; i <= max; i += 2) + { + isPrime[i] = false; + } + + int squareRoot = (int)Math.Sqrt(max); + for(int i = 3; i <= squareRoot; i += 2) + { + if(isPrime[i]) + { + for(int j = 2 * i; j <= max; j += i) + { + isPrime[j] = false; + } + } + } + + List primeNumbers = isPrime.Select((value, index) => new { value, index }) + .Where(obj => obj.value == true) + .Select(obj => obj.index) + .ToList(); + + return primeNumbers; + } + + public static void Main() + { + List primeNumbers = PrimeGenerator(100); + Console.WriteLine(string.Join(", ", primeNumbers)); + } + } +} diff --git a/algorithms/CSharp/test/Number-Theory/sieve-of-eratosthenes.cs b/algorithms/CSharp/test/Number-Theory/sieve-of-eratosthenes.cs new file mode 100644 index 00000000..6775e094 --- /dev/null +++ b/algorithms/CSharp/test/Number-Theory/sieve-of-eratosthenes.cs @@ -0,0 +1,16 @@ +using NUnit.Framework; +using System.Collections.Generic; + +namespace Algorithms.Tests.NumberTheory +{ + [TestFixture] + public class SieveOfEratosthenes + { + [TestCase(100, "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")] + public void SieveOfEratosthenes_ShouldReturnExpected(int max, string expected) + { + List primeNumbers = Algorithms.NumberTheory.SieveOfEratosthenes.PrimeGenerator(max); + Assert.AreEqual(expected, string.Join(", ", primeNumbers)); + } + } +}