11using System ;
22using System . Collections . Generic ;
3+ using System . Linq ;
34
45/***
56* Generates all prime numbers up to a given number
@@ -14,43 +15,43 @@ public static class SieveOfEratosthenes
1415 /// <summary>
1516 /// Calculate primes up to a given number
1617 /// </summary>
17- public static List < int > GeneratePrimesUpTo ( int x )
18+ public static IEnumerable < int > GeneratePrimesUpTo ( int x )
1819 {
1920
20- //The list of primes that will be returned
21- List < int > primesList = new List < int > ( ) ;
21+ //The hash of primes that will be returned
22+ var primes = new HashSet < int > ( ) ;
2223
2324 //Returns an empty list if x is a value under 2
2425 if ( x < 2 )
2526 {
26- return primesList ;
27+ return primes . ToList ( ) ;
2728 }
2829
29- //Adds every number between 2 and x to the list
30+ //Adds every number between 2 and x to the hashset
3031 for ( int i = 2 ; i <= x ; i ++ )
3132 {
32- primesList . Add ( i ) ;
33+ primes . Add ( i ) ;
3334 }
3435
35- //integer that all multiples of will be removed from the list
36+ //integer that all multiples of will be removed from the hashset
3637 int removeMultiplesOf ;
3738
38- //Finds the next number in the list that hasn't been removed and removes all multiples of that number
39- //from the list
39+ //Finds the next number that hasn't been removed and removes all multiples of that number
40+ //from the hashset
4041 for ( int i = 2 ; i <= Math . Sqrt ( x ) ; i ++ )
4142 {
42- if ( primesList . Contains ( i ) )
43+ if ( primes . Contains ( i ) )
4344 {
4445 removeMultiplesOf = i ;
45- for ( int j = removeMultiplesOf * removeMultiplesOf ; j <= x ; j += removeMultiplesOf )
46+ for ( int j = removeMultiplesOf * removeMultiplesOf ; j <= x ; j += removeMultiplesOf )
4647 {
47- primesList . Remove ( j ) ;
48+ primes . Remove ( j ) ;
4849 }
4950 }
5051 }
5152
5253 //The list of primes is returned
53- return primesList ;
54+ return primes . ToList ( ) ;
5455 }
5556
5657 }
0 commit comments