I'm having trouble optimising the project euler #50 exercise, it runs for around 30-35 seconds, which is terrible performance.
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most consecutive primes?
The catch here is that it's not necessary to start from 2, the sum of consecutive primes which add to 953 are starting from 7.
Here's my code :
static void Main(string[] args)
{
int max = 0;
int maxCount = 1;
List<int> primes = new List<int>();
Stopwatch sw = Stopwatch.StartNew();
bool[] allNumbers = SetPrimes(1000000);
for (int i = 0; i < allNumbers.Length; i++)
{
if (allNumbers[i])
{
primes.Add(i);
}
}
foreach (int prime in primes)
{
int startingIndex = 0;
while (primes[startingIndex] < prime/maxCount)
{
int n = prime;
int j = startingIndex;
int sum = 0;
int count = 0;
while (n > 0)
{
sum += primes[j];
n -= primes[j];
j++;
count++;
}
if (sum == prime)
{
if (count > maxCount)
{
maxCount = count;
max = prime;
}
}
startingIndex++;
}
}
sw.Stop();
Console.WriteLine(max);
Console.WriteLine($"Time to calculate : {sw.ElapsedMilliseconds}");
Console.ReadKey();
}
private static bool[] SetPrimes(int max)
{
bool[] localPrimes = new bool[max + 1];
for (int i = 2; i <= max; i++)
{
localPrimes[i] = true;
}
for (int i = 2; i <= Math.Sqrt(max); i++)
{
if (localPrimes[i])
{
for (int j = i * i; j <= max; j += i)
{
localPrimes[j] = false;
}
}
}
return localPrimes;
}