/// <summary> /// Finds all the prime numbers up to maxNumber. /// If the number is larger than n, an out of memory exception will be thrown, based on the current available memory. /// </summary> /// <param name="maxNumber"></param> /// <returns></returns> private List <long> SieveOfEratostenes(int maxNumber) { Int64[] result = new Int64[maxNumber + 1]; HashSet <Int64> nonPrimes = new HashSet <Int64>(); for (Int64 i = 2; i < maxNumber + 1; i++) { result[i - 2] = i; } for (Int64 i = 0; i < result.Length; i++) { int p = 2; if (!nonPrimes.Contains(result[i])) { while (p <= maxNumber) { Int64 x = result[i] * p; p++; if (x <= maxNumber && !nonPrimes.Contains(x)) { nonPrimes.Add(x); } } } } var finalResult = result.Except(nonPrimes); Console.WriteLine(); foreach (int elem in finalResult) { Console.Write(elem + ", "); } Console.ReadLine(); return(finalResult.ToList()); }