1
1
using System ;
2
2
using System . Collections . Generic ;
3
+ using System . Linq ;
3
4
4
5
/***
5
6
* Generates all prime numbers up to a given number
@@ -14,43 +15,43 @@ public static class SieveOfEratosthenes
14
15
/// <summary>
15
16
/// Calculate primes up to a given number
16
17
/// </summary>
17
- public static List < int > GeneratePrimesUpTo ( int x )
18
+ public static IEnumerable < int > GeneratePrimesUpTo ( int x )
18
19
{
19
20
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 > ( ) ;
22
23
23
24
//Returns an empty list if x is a value under 2
24
25
if ( x < 2 )
25
26
{
26
- return primesList ;
27
+ return primes . ToList ( ) ;
27
28
}
28
29
29
- //Adds every number between 2 and x to the list
30
+ //Adds every number between 2 and x to the hashset
30
31
for ( int i = 2 ; i <= x ; i ++ )
31
32
{
32
- primesList . Add ( i ) ;
33
+ primes . Add ( i ) ;
33
34
}
34
35
35
- //integer that all multiples of will be removed from the list
36
+ //integer that all multiples of will be removed from the hashset
36
37
int removeMultiplesOf ;
37
38
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
40
41
for ( int i = 2 ; i <= Math . Sqrt ( x ) ; i ++ )
41
42
{
42
- if ( primesList . Contains ( i ) )
43
+ if ( primes . Contains ( i ) )
43
44
{
44
45
removeMultiplesOf = i ;
45
- for ( int j = removeMultiplesOf * removeMultiplesOf ; j <= x ; j += removeMultiplesOf )
46
+ for ( int j = removeMultiplesOf * removeMultiplesOf ; j <= x ; j += removeMultiplesOf )
46
47
{
47
- primesList . Remove ( j ) ;
48
+ primes . Remove ( j ) ;
48
49
}
49
50
}
50
51
}
51
52
52
53
//The list of primes is returned
53
- return primesList ;
54
+ return primes . ToList ( ) ;
54
55
}
55
56
56
57
}
0 commit comments