Skip to content

Instantly share code, notes, and snippets.

@vczh
Created December 1, 2016 06:29
Show Gist options
  • Save vczh/9c4694e19d009ade768bae7f65f9b6cc to your computer and use it in GitHub Desktop.
Save vczh/9c4694e19d009ade768bae7f65f9b6cc to your computer and use it in GitHub Desktop.
The prime 41
#include <iostream>
#include <type_traits>
using namespace std;
const int Max = 1000;
bool isPrime[Max];
int primes[Max] = { 0 };
int primeCount = 0;
int minIndex = 0;
int maxIndex = 0;
int seqIndex = 0;
int sums[Max][Max] = { 2 };
void FillPrimes()
{
isPrime[0] = false;
isPrime[1] = false;
for (int i = 2; i < Max; i++)
{
isPrime[i] = true;
}
for (int i = 2; i < Max; i++)
{
if (isPrime[i])
{
for (int j = i * 2; j < Max; j += i)
{
isPrime[j] = false;
}
}
}
for (int i = 2; i < Max; i++)
{
if (isPrime[i])
{
primes[primeCount++] = i;
}
}
}
void PrintResult()
{
for (int i = minIndex; i < maxIndex; i++)
{
cout << primes[i] << " + ";
}
cout << primes[maxIndex] << " = " << sums[minIndex][maxIndex] << endl;
}
void SetSum(int first, int last, int sum)
{
sums[first][last] = sum;
if (isPrime[sum] && ((last)-(first)) > (maxIndex - minIndex))
{
minIndex = first;
maxIndex = last;
PrintResult();
}
}
int main()
{
FillPrimes();
for (int i = 1; i < primeCount; i++)
{
int prime = primes[i];
int sum = sums[seqIndex][i - 1] + prime;
while (sum >= Max)
{
sum -= primes[seqIndex];
seqIndex++;
}
if (seqIndex == i)
{
int newSum = prime;
SetSum(seqIndex, i, newSum);
}
else
{
{
int newSum = prime + sums[seqIndex][i - 1];
SetSum(seqIndex, i, newSum);
}
for (int j = seqIndex; j < i; j++)
{
int newSum = sums[seqIndex][i] - sums[seqIndex][j];
SetSum(j + 1, i, newSum);
}
}
}
PrintResult();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment