Is there a built in function that can generate a random prime number between 2 given limits in C/C++?
I want a function that can generate a random prime number between 1 million and 1 billion
Is there a built in function that can generate a random prime number between 2 given limits in C/C++?
I want a function that can generate a random prime number between 1 million and 1 billion
You can do this efficiently like so:
2 .. 17
, experiment for best results). If yes, go to 1;Also see this for a similar, a bit more complex, idea.
When I had to do this I created a function called isPrime(). isPrime() would check and determine if a number was prime.
isPrime() had two different functions one that would run forever and print every prime number and another that would run up to a certain number.
You could populate an array with all of the prime numbers between i and j. Then generate a random number that is less than or equal to the size of the array. Use this random number to select an element from the array.
Hope this helps!
To generate a random number between two bounds do this
extern unsigned int urand();
int lower = 1000000;
int upper = 1000000000;
int p = urand() % (upper - lower) + lower;
To test if a number near 1 billion is prime it is sufficient to do trial division by all primes < sqrt(1 billion) = 31622. There are about 3400 such primes. Make an array
unsigned short primes[3400] = { 2, 3, 5, .. 31657 }
and divide by them all. If all trial divisions have remainder != 0 then the number is prime.
I doubt any of the more sophisticated primality tests will be faster for such small primes.