Trying to generate a random prime p in the range [2,2147483647] using the C++11 std::uniform_int_distribution.
It's been commented that this approach might not be correct:
It is not immediately obvious that this p is uniformly distributed over the set of all primes <= 2^31 - 1. Whatever uniformity and bias guarantees the random-number generator has, they refer to all integers within the range, but the code is "sieving" just the primes out of it.
However, from another similar S.O. article, it notes
As long as the input random numbers are uniformly distributed in the range, the primes chosen by this method will be uniformly distributed among the primes in that range, too.
Question
Is this code truly correct to generate a random prime?
https://onlinegdb.com/FMzz78LBq
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <time.h>
#include <random>
int isPrimeNumber (int num)
{
if (num == 1) return 0;
for (int i = 2; i <= sqrt (num); i++)
{
if (num % i == 0)
{
// not prime
return 0;
}
}
// prime
return 1;
}
int main ()
{
std::random_device rd;
std::mt19937 rng (rd ());
// Define prime range from 2 to 2^31 - 1.
std::uniform_int_distribution<int>uni (2, 2147483647);
int prime;
// Generate a random prime.
do { prime = uni(rng); } while (!isPrimeNumber(prime));
printf ("prime = %d", prime);
return 0;
}