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

早过忘川 提交于 2019-12-05 05:29:12

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!