-1

This function is supposed to take in three parameters and find the prime numbers less than the NUM inputed using trial division

void trialDivision(int prime[], const int NUM, const int SIZE) {
int j = NUM;
for (int i = 0; i < NUM; i++) {
    prime[i] = 1;
}

for (int i = 2; i <= sqrt(NUM); i++, j++) {
    put numbers less than n into array
}

Then do trial division to find prime numbers.

I am having a problem figuring out how to put numbers less than sqrt(NUM) into a function.

Thanks

Carlos
  • 5,991
  • 6
  • 43
  • 82
  • Are you trying to implement Sieve of Eratosthenes? Google it and you'll find many examples. Or start with Wikipedia. – Barmar Feb 12 '16 at 22:00

1 Answers1

0

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.

Chara
  • 1,045
  • 10
  • 21