0

Hi everyone! I am working my way through some problems from projecteuler.net and came across one that has stalled me. The task is to find the sum of all primes under 2,000,000.

I am attempting to use the Sieve of Eratosthenes algorithm for identifying prime numbers.

Here is my code so far:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Euler10._1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Run();
        }

        public void Run()
        {
            int primeSum = 0;
            int limit = 2000000;

            List<int> primeList = SieveOfEratosthenes(limit);

            foreach (int prime in primeList)
            {
                primeSum += prime;
            }

            Console.WriteLine("Sum of primes under limit ({0}) is: {1}", limit, primeSum);
        }

        public List<int> SieveOfEratosthenes(int limit)
        {            
            //List<bool> primeNumbers = new List<bool>();

            //primeNumbers.Add(false);
            //primeNumbers.Add(false);

            // create bool array to store whether value is prime or not 
            bool[] primeNumbers = new bool[limit];
            for (int i = 2; i < limit; i++)
            {
                primeNumbers[i] = true;
            }

           // BitArray primeNumbers = new BitArray(limit, true);

            primeNumbers[0] = false;
            primeNumbers[1] = false;

            for (long i = 2; i < limit; i++)
            {
                if (primeNumbers[i])
                {
                    for (long j = i * i; j < limit; j += i)
                    {
                        primeNumbers[j] = false;
                    }
                }
            }

            List<int> primeList = new List<int>();

            for (int i = 2; i < limit; i++)
            {
                if (primeNumbers[i] == true)
                {
                    primeList.Add(i);
                }
            }

            return primeList;           
        }
    }
}

If I use 1,000,000 for the limit, it returns "-1104303641" as the sum, which is odd because it is negative. I may be missing something obvious here, so I'm sorry in advance if that is the case.

Any thoughts?

1
Contributor
1
Reply
2
Views
7 Years
Discussion Span
Last Post by nwhitesel
0

I changed the sum counter from an int to a long. der-der-der.

Thanks anyway if you looked and put any time in.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.