Primality Test | Set 3 ( Millerâ €“ Rabin ) | Python3 program Miller - Rabin primality test ; Utility function to do modular exponentiation . It returns ( x ^ y ) % p ; Initialize result ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; This function is called for all k trials . It returns false if n is composite and returns false if n is probably prime . d is an odd number such that d * 2 < sup > r < / sup > = n - 1 for some r >= 1 ; Pick a random number in [ 2. . n - 2 ] Corner cases make sure that n > 4 ; Compute a ^ d % n ; Keep squaring x while one of the following doesn 't  happen  (i) d does not reach n-1  (ii) (x^2) % n is not 1  (iii) (x^2) % n is not n-1 ; Return composite ; It returns false if n is composite and returns true if n is probably prime . k is an input parameter that determines accuracy level . Higher value of k indicates more accuracy . ; Corner cases ; Find r such that n = 2 ^ d * r + 1 for some r >= 1 ; Iterate given nber of ' k ' times ; Driver Code Number of iterations
import random NEW_LINE def power ( x , y , p ) : NEW_LINE INDENT res = 1 ; NEW_LINE x = x % p ; NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p ; NEW_LINE DEDENT x = ( x * x ) % p ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def miillerTest ( d , n ) : NEW_LINE INDENT a = 2 + random . randint ( 1 , n - 4 ) ; NEW_LINE x = power ( a , d , n ) ; NEW_LINE if ( x == 1 or x == n - 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT while ( d != n - 1 ) : NEW_LINE INDENT x = ( x * x ) % n ; NEW_LINE d *= 2 ; NEW_LINE if ( x == 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if ( x == n - 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT def isPrime ( n , k ) : NEW_LINE INDENT if ( n <= 1 or n == 4 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT d = n - 1 ; NEW_LINE while ( d % 2 == 0 ) : NEW_LINE INDENT d //= 2 ; NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT if ( miillerTest ( d , n ) == False ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT k = 4 ; NEW_LINE print ( " All ▁ primes ▁ smaller ▁ than ▁ 100 : ▁ " ) ; NEW_LINE for n in range ( 1 , 100 ) : NEW_LINE INDENT if ( isPrime ( n , k ) ) : NEW_LINE INDENT print ( n , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT