# generate random prime number python

Do you want to know the details regarding “generate random prime number python”. If yes, you’re in the correct post.

## generate random prime number python

``````# Prime number generator
def prime_generator(end):
for n in range(2, end):     # n starts from 2 to end
for x in range(2, n):   # check if x can be divided by n
if n % x == 0:      # if true then n is not prime
break
else:                   # if x is found after exhausting all values of x
yield n             # generate the prime

g = prime_generator(1000)       # give firt 1000 prime numbers
print(list(g)) ``````
``````import sympy

primeNumber = sympy.randprime(min, max)
``````
``````# effiecent and fast way to generate prime numbers
def primeCheck(n):
if n == 1 or n == 0 or (n % 2 == 0 and n > 2):
return False
else:
for o in range(3, int(n ** (1 / 2)) + 1, 2):
if n % o == 0:
return False
return True

for a in range(2**15):
if primeCheck(a):
prime_numbers.append(a)``````
``````def miller_rabin(n, k):

# Implementation uses the Miller-Rabin Primality Test
# The optimal number of rounds for this test is 40
# See http://stackoverflow.com/questions/6325576/how-many-iterations-of-rabin-miller-should-i-use-for-cryptographic-safe-primes
# for justification

# If number is even, it's a composite number

if n == 2 or n == 3:
return True

if n % 2 == 0:
return False

r, s = 0, n - 1
while s % 2 == 0:
r += 1
s //= 2
for _ in range(k):
a = random.randrange(2, n - 1)
x = pow(a, s, n)
if x == 1 or x == n - 1:
continue
for _ in range(r - 1):
x = pow(x, 2, n)
if x == n - 1:
break
else:
return False
return True

"""
a function that uses miller rabin's primality test to genarate a prime number in a certain number of bits length
in other words you give it a number of bits and you will get a prime number with that number of bits
"""
def genprimeBits(k):
x = ""
k = int(k)
for y in range(k):
x = x + "1"
y = "1"
for z in range(k-1):
y = y + "0"
x = int(x,2)
y = int(y,2)
p = 0
while True:
p = random.randrange(y,x)
if miller_rabin(p,40):
break
return p``````

## Conclusion

I hope this tutorial helps you to know about “generate random prime number python”. If you have any queries regarding this post please let us know via the comment section. Share this post with your friends & family via social networks. Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coder Diksha. Here, I post about programming to help developers.

Share on: