I'm so happy that I stumbled upon Project Euler. It gives me many projects that I can sink my time into, allows me to learn more math (which I love), and has the added benefit of forcing me to optimize my code for speed.
I'm on problem number 10 now. Finding the sum of all primes below two million. Earlier problems involving primes were easy, and calculated pretty quickly, as the prime never really got too high. However.. two million..
So my question is, how can I optimize my code here? I'm using C#, by the way.
static void Main(string[] args)
{
long prime = 2;
long sum = 0;
bool isPrime;
do
{
isPrime = true;
Console.WriteLine("Prime: {0} Sum: {1}", prime, sum);
for (int i = 1; i < prime; i++)
{
if (i == 1 || i == prime)
continue;
if (prime % i == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
sum += prime;
prime++;
Console.Clear();
}
while (prime <= 2000000);
Console.WriteLine("Prime: {0} Sum: {1}", prime, sum);
Console.ReadLine();
}
I don't even know what else I could use to make it run faster..
It's currently been running for about.. 5-7 minutes now, and the prime number is only at ~630,000.
It's not a necessity, I would just like to know if it's possible, or if it's just going to take a bit no matter what because the limit is so high.
Thanks to anybody taking the time on this! Happy to be back =)
This post has been edited by Guitartripp: 16 August 2012 - 08:24 PM

New Topic/Question
Reply




MultiQuote





|