how to generate prime numbers in a bit range python

Solutions on MaxInterview for how to generate prime numbers in a bit range python by the best coders in the world

showing results for - "how to generate prime numbers in a bit range python"
Amy
18 Jul 2016
1def miller_rabin(n, k):
2
3    # Implementation uses the Miller-Rabin Primality Test
4    # The optimal number of rounds for this test is 40
5    # See http://stackoverflow.com/questions/6325576/how-many-iterations-of-rabin-miller-should-i-use-for-cryptographic-safe-primes
6    # for justification
7
8    # If number is even, it's a composite number
9
10    if n == 2 or n == 3:
11        return True
12
13    if n % 2 == 0:
14        return False
15
16    r, s = 0, n - 1
17    while s % 2 == 0:
18        r += 1
19        s //= 2
20    for _ in range(k):
21        a = random.randrange(2, n - 1)
22        x = pow(a, s, n)
23        if x == 1 or x == n - 1:
24            continue
25        for _ in range(r - 1):
26            x = pow(x, 2, n)
27            if x == n - 1:
28                break
29        else:
30            return False
31    return True
32
33"""
34a function that uses miller rabin's primality test to genarate a prime number in a certain number of bits length
35in other words you give it a number of bits and you will get a prime number with that number of bits
36"""
37def genprimeBits(k):
38    x = ""
39    k = int(k)
40    for y in range(k):
41        x = x + "1"
42    y = "1"
43    for z in range(k-1):
44        y = y + "0"
45    x = int(x,2)
46    y = int(y,2)
47    p = 0
48    while True:
49        p = random.randrange(y,x)
50        if miller_rabin(p,40):
51            break
52    return p