I need to write a program that figures out how many prime numbers exist within an arbitrary, random range of numbers.

#include <iostream>
#include <time.h>

using namespace std;

int main()
{
srand(time(NULL));
int lowerLimit = -(rand() % 100 + 1);
int upperLimit = rand() % 100 + 1;
{
for (int i = 2; i < 100; i++)


cout << "The number of primes between " << lowerLimit << " and " << upperLimit << " is ___\n\n";
}

system("PAUSE");
return 0;
}
How accurate does your answer have to be?

Is your range actually restricted to about -100 to about 100, or is that just an example?
Last edited on
If you need to write such, then you need to. Did you have a question?


I do not recall seeing negative primes. That makes your lower limit suspicious.


C++ has header <ctime>. It might be a simple wrapper for <time.h>, or it might not. It is recommended to use the <ctime>.


There is an another recommendation: use <random> rather than the <ctime>.
See http://www.cplusplus.com/reference/random/

You are learning C++, are you not? If yes, then you should learn modern C++ and not C. The <random> is modern C++.
The only way to know the number of primes in any given range is to count them. To count them, you must test all the numbers in that range.

Unless your professor expects you to use something fancy like a Miller-Rabin test, or to use Boost bigintegers for the primality test function, you can safely assume that this assignment is only expected to work over something like unsigned long and for you to write a simple prime number generator.

Do this by keeping a list (a std::vector will do) of numbers you have discovered to be prime. Initialize it with at least the first two prime nimbers: 2 and 3. (I recommend more, but any more than two is strictly unnecessary.)

Next, write a function called "isprime" or similar :
1
2
3
4
  bool isprime( unsigned long n )
  {
    ...
  }

If 'n' is less than the largest number in the list, then you can check for primality just by checking whether or not it is in the list.

If it is larger, then start counting, starting with the value of the largest item+1. For each item less than or equal to 'n', try evenly dividing it by every item in the list. Whenever you find a new prime, add it to the list. By the time you are done, 'n' will either be in the list of primes or it won't.

Now you have the tool to determine how many primes exist between any range. Just call isprime() for the upper bound on the range. Next, find the first number in the list greater than or equal to the lower bound, and the number of primes is the length of the list from the lower number to the enhope this helps.
Topic archived. No new replies allowed.