First, you're going to want to create a loop that goes from i=2
to i<NUM
. This is to check every positive integer greater than 1 up to NUM-1 for primeness. It would look something like this:
for (int i=2;i<NUM;i++)
{
// prime checking
}
Now for the actual prime checking. Let's put this in a function. This is where you would use sqrt()
to define the upper bound of the loop. Once again we start our loop at j=2
because all numbers are divisible by 1, so there's no need to include that.
bool isPrime(int i)
{
for (int j=2;j<sqrt(i);j++)
{
if (i%j==0)
{
return false;
}
}
return true;
}
Basically, if the loop terminates, then we have not found any factors of i
between 2
and sqrt(i)
, so it is prime.
Now simply call this function in your first loop.
for (int i=2;i<NUM;i++)
{
if (isPrime(i))
{
prime[i] = 1; // or whatever you want to use to represent a prime. If you use 1, it's best if you initiate the array with 0's
}
}
If you wanted just a list of primes, then std::vector<int>
would be a better choice for storing your results.