//Requires: n >= 0
//Modifies: nothing
//Effects: returns the sum of the first 'n' primes
// a parameter of 5 will return
// 2 + 3 + 5 + 7 + 11 or 28
One of my previous functions is
1 2 3 4 5 6 7 8 9 10 11 12
bool isPrime(int val)
{ int i;
for (i=2; i<val; i++)
{
if (val % i == 0)
{
returnfalse;
}
}
returntrue;
}
I am really at a loss for how to approach this. I thought about using something like for(int numberOfPrimes = 0; numberOfPrimes <= n; numberOfPrimes++)
But I don't really know how to get 'n' primes. I have an idea with while-loops, as in while (isPrime != true), then going up till it was true. But I can't seem to figure out how to keep that count so when it would loop back to that segment again, it would continue where it left off.
Any suggestions as to how to make the while loop continue from where it started?
Your suggested for loop for(int numberOfPrimes = 0; numberOfPrimes <= n; numberOfPrimes++) won't work because then 0 and 1 would test positive for being prime but they are not. You simply need another variable in your function to count the number of prime numbers you've calculated and an array to return them in, personally I have an isPrime(...) function that only tests the integer passed to it for primeness and returns true of false, I use another function to gather the numbers together. Wikipedia has an excellent article on formulas and methods for finding Prime numbers, if you have some spare time it's worth a read. http://en.wikipedia.org/wiki/Prime#Testing_primality_and_integer_factorization