primes

Python code posted by beardedp
created at 04 Dec 05:18, updated at 07 Dec 10:31

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def miller_rabin_prime(n):
    """Implementation of the Miller-Rabin probalistic primality
    test. http://en.wikipedia.org/wiki/Miller-Rabin_primality_test"""
    if n % 2 and n > 3:
        # Odd number greater than 3
        k = 3 # Decide accuracy of our test

        #write n - 1 as 2s*d with d odd by factoring powers of 2 from n - 1
        n1, s, d = n - 1, 0, 0
        while True:
            if not n1 % 2:
                s += 1
                n1 //= 2
            else:
                d = n1
                break

        for _ in range(k):
            a = randint(2, n - 1)
            x = pow(a, d, n)

            if x not in (1, n - 1):
                for _ in range(s):
                    x = pow(x, 2, n)
                    if x == 1:
                        return False
                    elif x == n -1:
                        break
                else:
                    return False

        # n is probably prime
        return True
    else:
        # 2 or 3 are the only prime numbers that will fall in here.
        return n in (2, 3)
1.09 KB in 2 ms with coderay