A simple prime-number bot, in python. WIP
mastodon
python
fediverse
bot
mathematics
prime-numbers

bot.py 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import random
  2. pto100 = [
  3. 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
  4. 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
  5. ]
  6. def in_100(x):
  7. """Check if x is in the primes less than 100 i.e., in the first 25 primes.
  8. Useful for e.g. the first step in Baillie–PSW.
  9. """
  10. return x in pto100
  11. def hund_div(x):
  12. """Check if x is divisible by any of the 25 primes less than 100. Returns 0
  13. if there is no such divisor, otherwise returns the first divisor.
  14. """
  15. for v in pto100:
  16. if v >= x:
  17. return 0
  18. if x % v == 0:
  19. return v
  20. return 0
  21. def trd(x):
  22. """Express x as 2^r * d. Returns two values, r and d.
  23. """
  24. count = 0
  25. xc = x
  26. while xc % 2 == 0:
  27. count = count + 1
  28. xc = xc // 2
  29. return count, xc
  30. def MillerRabinRandom(n, k):
  31. """Carry out a Miller-Rabin test on n with k iterations, choosing random
  32. values for a.
  33. """
  34. r, d = trd(n-1)
  35. for iter in range(k):
  36. a = random.randint(2, n - 2)
  37. x = pow(a, d, n)
  38. if x == 1 or x == n - 1:
  39. continue
  40. compo = True
  41. for iterb in range(r - 1):
  42. x = pow(x, 2, n)
  43. if x == n - 1:
  44. compo = False
  45. break
  46. if compo:
  47. return True
  48. return False
  49. def MillerRabin(n, base):
  50. """Carry out a Miller-Rabin test on n with a specified base.
  51. """
  52. r, d = trd(n-1)
  53. a = base
  54. x = pow(a, d, n)
  55. if x == 1 or x == n - 1:
  56. return False
  57. for iterb in range(r - 1):
  58. x = pow(x, 2, n)
  59. if x == n - 1:
  60. return False
  61. return True
  62. # Print pseudoprimes greater than 100 for each base, from base 1 to 15
  63. for base in range(2, 16):
  64. print("{}:".format(base))
  65. for i in range(2, 10000):
  66. if i % 2 == 0 or base % i == 0:
  67. continue
  68. if MillerRabin(i, base) == (hund_div(i) == 0):
  69. print(i, hund_div(i), MillerRabin(i, base))
  70. print()
  71. MillerRabin(28, 3)
  72. print(pow(3, 27, 28))
  73. print(pow(3, 27))
  74. print(pow(3, 27) % 28)