Friday 10 April 2009

PROJECT EULER #10

Link to Project Euler problem 10

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.

Prime question no. 3. Use the sieve to generate them, then add them up. Simple.

using System;
using System.Collections.Generic;

namespace ProjectEuler
{
class Program
{
static void Main(string[] args)
{
//Problem 10
DateTime start = DateTime.Now;
List<int> primes= new List<int>() { 2, 3 };
long sum = 0;

for (int i = 5; i < 2000000; i += 2)
{
primes.Add(i);
foreach (int j in primes)
{
if (i % j == 0 && i != j)
{
primes.Remove(i);
break;
}
}
}
foreach (int k in primes)
{
sum += k;
}
TimeSpan time = DateTime.Now-start;
Console.WriteLine("{0}\nThis took {1}", sum, time);
Console.ReadKey();
}
}
}

No comments: