Advertisement
jukaukor

Miller_Rabin_isprime.py

Mar 23rd, 2019
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. # Miller-Rabin correct and probabilistic composite, prime test
  2. # correct answers for n less than 341550071728321
  3. # and then reverting to the probabilistic form
  4. # source https://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test#Python
  5. def _try_composite(a, d, n, s):
  6. if pow(a, d, n) == 1:
  7. return False
  8. for i in range(s):
  9. if pow(a, 2**i * d, n) == n-1:
  10. return False
  11. return True # n is definitely composite
  12.  
  13. def is_prime(n, _precision_for_huge_n=16):
  14. if n in _known_primes:
  15. return True
  16. if any((n % p) == 0 for p in _known_primes) or n in (0, 1):
  17. return False
  18. d, s = n - 1, 0
  19. while not d % 2:
  20. d, s = d >> 1, s + 1
  21. # Returns exact according to http://primes.utm.edu/prove/prove2_3.html
  22. if n < 1373653:
  23. return not any(_try_composite(a, d, n, s) for a in (2, 3))
  24. if n < 25326001:
  25. return not any(_try_composite(a, d, n, s) for a in (2, 3, 5))
  26. if n < 118670087467:
  27. if n == 3215031751:
  28. return False
  29. return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7))
  30. if n < 2152302898747:
  31. return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11))
  32. if n < 3474749660383:
  33. return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13))
  34. if n < 341550071728321:
  35. return not any(_try_composite(a, d, n, s) for a in (2, 3, 5, 7, 11, 13, 17))
  36. # otherwise
  37. return not any(_try_composite(a, d, n, s)
  38. for a in _known_primes[:_precision_for_huge_n])
  39.  
  40. _known_primes = [2, 3]
  41. _known_primes += [x for x in range(5, 1000, 2) if is_prime(x)]
  42.  
  43. number = int(input("Anna positiivinen kokonaisluku, jonka jaollisuus testataan "))
  44. print("Luku ",number," on alkuluku: ",is_prime(number))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement