diff --git a/Algorithms/Numeric/SieveOfEratosthenes.cs b/Algorithms/Numeric/SieveOfEratosthenes.cs new file mode 100644 index 00000000..18bcfc87 --- /dev/null +++ b/Algorithms/Numeric/SieveOfEratosthenes.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; + +/*** +* Generates all prime numbers up to a given number +* Wikipedia: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes +*/ + + +namespace Algorithms.Numeric +{ + public static class SieveOfEratosthenes + { + /// + /// Calculate primes up to a given number + /// + public static List GeneratePrimesUpTo(int x) + { + + //The list of primes that will be returned + List primesList = new List(); + + //Returns an empty list if x is a value under 2 + if (x < 2) + { + return primesList; + } + + //Adds every number between 2 and x to the list + for (int i = 2; i <= x; i++) + { + primesList.Add(i); + } + + //integer that all multiples of will be removed from the list + int removeMultiplesOf; + + //Finds the next number in the list that hasn't been removed and removes all multiples of that number + //from the list + for (int i = 2; i <= Math.Sqrt(x); i++) + { + if (primesList.Contains(i)) + { + removeMultiplesOf = i; + for (int j = removeMultiplesOf*removeMultiplesOf; j <= x; j += removeMultiplesOf) + { + primesList.Remove(j); + } + } + } + + //The list of primes is returned + return primesList; + } + + } +} diff --git a/MainProgram/AlgorithmsTests/SieveOfEratosthenesTest.cs b/MainProgram/AlgorithmsTests/SieveOfEratosthenesTest.cs new file mode 100644 index 00000000..44a1cf03 --- /dev/null +++ b/MainProgram/AlgorithmsTests/SieveOfEratosthenesTest.cs @@ -0,0 +1,33 @@ +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; + +namespace C_Sharp_Algorithms.AlgorithmsTests +{ + class SieveOfEratosthenesTest + { + + //Test lists + static List testList = new List(); + static List primesUpTo100List = new List{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}; + static List primesUpTo2List = new List { 2 }; + static List emptyList = new List(); + + public static void DoTest() + { + //Check if algorithm returns expected lists + testList = Algorithms.Numeric.SieveOfEratosthenes.GeneratePrimesUpTo(100); + Debug.Assert(testList.SequenceEqual(primesUpTo100List)); + + testList = Algorithms.Numeric.SieveOfEratosthenes.GeneratePrimesUpTo(2); + Debug.Assert(testList.SequenceEqual(primesUpTo2List)); + + testList = Algorithms.Numeric.SieveOfEratosthenes.GeneratePrimesUpTo(1); + Debug.Assert(testList.SequenceEqual(emptyList)); + + testList = Algorithms.Numeric.SieveOfEratosthenes.GeneratePrimesUpTo(-100); + Debug.Assert(testList.SequenceEqual(emptyList)); + + } + } +}