Ash Ash - 3 years ago 146
C++ Question

Trying to obtain sum of random prime numbers read from a file?

I am trying to read a random amount of numbers from a list in a file. From those numbers, I need to decide whether or not the numbers themselves are prime, then I need to add all of the prime numbers together to get their sum.

I am having issues with this block of my code. I'm sort of lost on how to go about obtaining the values that ARE prime and storing them so I can add them together to get their cumulative sum. I think this part of the code would go in my

else if
block, but I'm not 100% sure. Would someone be able to point me in the right direction and/or give me an example? If I wanted to obtain their average, can I do so in a similar way to obtaining their sum?

Also, there are multiple values being pulled from my list, so if I use a single variable to represent a prime number, will the variable reset itself to the next prime number it finds every time the entire loop iterates?

bool primeCalc()
{
int number;
bool primeValue = true;
int i;
while (inputFile >> number)
{
for (i = 2; i <= number / 2; ++i)
{
if (number % i == 0)
{
primeValue = false;
break;
}
else if (number % i > 0)
{
// some code to store number value for sum;

}
}
}

Answer Source

Why store them and waste space? Do it as they come from the stream, like this:

int sum = 0;
while(inputFile >> number)
{
  if(isPrime(number))
    sum += (number);
}

where isPrime could be a function of this prototype: bool isPrime(int number);, which returns true if number is prime, otherwise false.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download