Hi, I've tried to write a code to answer the question:
"Which prime, below one-million, can be written as the sum of the most consecutive primes?"
But I've run into a few problems... (code is below)
- In compiling it says that "PrimeArray" and "iii" aren't declared in the "SumDown()" function. However, I already declared them in main(), so shouldn't that declare them in the function?
- Also, when I say:
Code:
int PrimeArray[50000];
int iii = 1;
PrimeArray[iii] = nNumber;
Apparently when I debugged it, it stayed as PrimeArray[iii], and did not become PrimeArray[1], how can I make this happen?
Here is the full code, by the way...
Thanks!
Code:
/*
Question:
Which prime, below one-million, can be written as the sum of the most consecutive primes?
Plan:
1. Define an array with 50000 elements
(a reasonable number considering there are about 78498 primes below one million)
2. Run a loop to test for Primes up to 50000.
3. Place each prime sequentially in the array.
4. After finding each new prime, add downwards in the array,
noting at each stage any new primes formed.
5. From this, take the record the largest sum that forms a prime in the downwards addition.
6. Continue this process, stopping when the largest prime exceeds 1,000,000.
7. Print the prime.
*/
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int nNumber) //this is a simple prime test, nothing too fancy
{
int nDivisorCount = 0;
for(int nDivisor = 2; nDivisor <= static_cast<int>(sqrt(static_cast<double>(nNumber))); nDivisor++)
{
if(nNumber % nDivisor == 0)
{
nDivisorCount += 1;
break;
}
}
if(nDivisorCount == 0)
return true;
else
return false;
}
int SumDown(int x) //sums down in the array from highest prime to lowest
{
int nPrimeSum = 0;
int nTermsInSum = 0;
int nMaxTermsInThisSum = 0;
for(int jjj = iii; jjj > 0; jjj--)
{
nTermsInSum += 1;
nPrimeSum += PrimeArray[jjj];
if (nPrimeSum >= 50000)
break;
if(isPrime(nPrimeSum) && (nTermsInSum > nMaxTermsInThisSum))
{
nMaxTermsInThisSum = nTermsInSum;
}
}
return nMaxTermsInThisSum;
}
int main()
{
int PrimeArray[50000];
PrimeArray[0] = 2; //take care of 2 since it's tricky
int nMaxTermsInAnySum = 0;
int nPrimeWithLongestSum;
int iii = 1; //denotes array slot into which primes are placed. Start at 1 because '2' has already been placed.
for(int nNumber = 3; nNumber <= 50000; nNumber++)
{
if(isPrime(nNumber))
{
PrimeArray[iii] = nNumber;
iii += 1;
if(SumDown(iii) > nMaxTermsInAnySum)
{
nMaxTermsInAnySum = SumDown(iii);
nPrimeWithLongestSum = nNumber;
}
}
}
cout << "The Prime " << nPrimeWithLongestSum << " can be expressed as the sum of " << nMaxTermsInAnySum << " primes." << endl;
return 0;
}