HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Sum of primes less than 2,000,000

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
primes000thanlesssum

Problem

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 all_numbers = new HashSet();
    public HashSet list_of_primes = new HashSet();
    public HashSet list_of_nonprimes = new HashSet();

    public Primes(int n)
    {
        all_numbers = new HashSet(Enumerable.Range(1, n));
        for (int i = 2; i (all_numbers.Except(list_of_nonprimes));
    }
}

Solution

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(ij). 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]==false

-
You 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.

Code Snippets

list_of_nonprimes.Add(i * j)
nonprimes[i*j] = true;

Context

StackExchange Code Review Q#25225, answer score: 2

Revisions (0)

No revisions yet.