I have been attempting the questions at Project Euler and I am trying to find the sum of Primes under two million (question 10)The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.Find the sum of all the primes below two million.Here is my attempt which does work, but I would like to know if there is any way to improve this code. Any suggestions welcomed!class SumOfPrimes{    static void Main(string[] args)    {        Primes primes = new Primes(2000000);        long sum = 0;        foreach(int p in primes.list_of_primes){            sum += p;        }        Console.WriteLine(sum);        Console.ReadLine();    }}class Primes{    public HashSet<int> all_numbers = new HashSet<int>();    public HashSet<int> list_of_primes = new HashSet<int>();    public HashSet<int> list_of_nonprimes = new HashSet<int>();    public Primes(int n)    {        all_numbers = new HashSet<int>(Enumerable.Range(1, n));        for (int i = 2; i < Math.Sqrt(n) + 1; i++)        {            for (int j = 3; j <= n / i; j++)                list_of_nonprimes.Add(i * j);        }        list_of_primes = new HashSet<int>(all_numbers.Except(list_of_nonprimes));    }}
Sum of primes less than 2,000,000
c#;primes;project euler
Some other things that you can try, short of trying a totally different algorithm:rename all_numbers to prime_candidates and remove composite numbers from it. (list_of_nonprimes.Add(i * j); -> prime_candidates.Remove(i*j). Avoiding the Except at the end. You can also hold which numbers are non primes in an array of bools and lose all the HashSets. Changing:list_of_nonprimes.Add(i * j)to nonprimes[i*j] = true;Thus avoiding a bunch of hash lookups. After the loops sum up any n s.t. nonprime[n]==falseYou can also use a BitArray instead of a bool array. Because it is more space efficient it might reduce cache misses.Of course, you can only be sure if any of these actually makes any improvement after you try.