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

牧云@^-^@ 提交于 2020-01-02 03:30:29

问题


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


回答1:


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.




回答2:


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!




回答3:


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.



来源:https://stackoverflow.com/questions/13665443/generate-random-prime-number-in-c-c-between-2-limits

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