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

bot.py 2.2KB

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