Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Random Prime number in C/C++ between 2 limits

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

like image 733
premprakash Avatar asked Dec 02 '12 01:12

premprakash


People also ask

How do you find a prime number between 2 numbers?

To find whether a larger number is prime or not, add all the digits in a number, if the sum is divisible by 3 it is not a prime number. Except 2 and 3, all the other prime numbers can be expressed in the general form as 6n + 1 or 6n - 1, where n is the natural number.


1 Answers

You can do this efficiently like so:

  1. Generate a random number in that interval;
  2. Check if it is divisible by any of the first few primes (say 2 .. 17, experiment for best results). If yes, go to 1;
  3. Use Miller-Rabin to test for primality.

Also see this for a similar, a bit more complex, idea.

like image 55
IVlad Avatar answered Sep 19 '22 07:09

IVlad