3 M(Y@sdZddlZddgZddZddZd d Zd dZd dZe d kre dddl Z x>e dD]2Z e j\ZZertPe r^e ddkr^e de q^We ddS)zNumerical functions related to primes. Implementation based on the book Algorithm Design by Michael T. Goodrich and Roberto Tamassia, 2002. Ngetprimeare_relatively_primecCs x|dkr|||}}qW|S)zPReturns the greatest common divisor of p and q >>> gcd(48, 180) 12 r)pqrr0/private/tmp/pip-build-nl73fm5q/rsa/rsa/prime.pygcds rcCs|dkr dS|d}d}x|d@s4|d7}|dL}qWxt|D]z}tjj|dd}t|||}|dks@||dkrzq@x>t|dD]*}t|d|}|dkrdS||dkrPqWdSq@WdS)a.Calculates whether n is composite (which is always correct) or prime (which theoretically is incorrect with error probability 4**-k), by applying Miller-Rabin primality testing. For reference and implementation example, see: https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test :param n: Integer to be tested for primality. :type n: int :param k: Number of rounds (witnesses) of Miller-Rabin testing. :type k: int :return: False if the number is composite, True if it's probably prime. :rtype: bool FrT)rangersarandnumrandintpow)nkdr_axrrrmiller_rabin_primality_testing(s(     rcCs&|dkr|dkS|d@sdSt|dS) aReturns True if the number is prime, and False otherwise. >>> is_prime(2) True >>> is_prime(42) False >>> is_prime(41) True >>> [x for x in range(901, 1000) if is_prime(x)] [907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997] r r F)r rrr)r)numberrrris_prime]s  rcCs.|dks txtjj|}t|r|SqWdS)aReturns a prime number that can be stored in 'nbits' bits. >>> p = getprime(128) >>> is_prime(p-1) False >>> is_prime(p) True >>> is_prime(p+1) False >>> from rsa import common >>> common.bit_size(p) == 128 True rN)AssertionErrorr rZread_random_odd_intr)nbitsintegerrrrr|s   cCst||}|dkS)zReturns True if a and b are relatively prime, and False if they are not. >>> are_relatively_prime(2, 3) True >>> are_relatively_prime(2, 4) False r )r)rbrrrrrs __main__z'Running doctests 1000x or until failureidz%i timesz Doctests done)__doc__Z rsa.randnumr __all__rrrrr__name__printdoctestr counttestmodZfailurestestsrrrrs" 5