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

lucas.py 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. # Finding lucas pseudoprimes
  2. from math import sqrt, gcd
  3. def isqrt(n):
  4. """ Find the integer square root of n via newton's method, code via
  5. stackoverflow:
  6. (https://stackoverflow.com/questions/15390807/integer-square-root-in-python)
  7. """
  8. x = n
  9. y = (x + 1) // 2
  10. while y < x:
  11. x = y
  12. y = (x + n // x) // 2
  13. return x
  14. def hasIntSQRT(n):
  15. """Detect whether the square root of n is an integer,
  16. i.e. whether the isqrt(n) is the true square root.
  17. """
  18. isq = isqrt(n)
  19. return isq * isq == n
  20. def Dsequence():
  21. """Generate sequence 5, -7, 9, -11, 13, -15...
  22. """
  23. val = 5
  24. while True:
  25. if val % 4 == 1:
  26. yield val
  27. else:
  28. yield -val
  29. val = val + 2
  30. def Legendre(a, p):
  31. """Function for calculating Legendre symbol.
  32. Note that this is only supposed to be defined if p is an odd prime, but we
  33. don't know in advance if that is true - will therefore only throw and error
  34. if p is even.
  35. Uses original power definition from
  36. <https://en.wikipedia.org/wiki/Legendre_symbol>
  37. """
  38. if (p % 2 == 0):
  39. raise ValueError("p must be odd, is {}".format(p))
  40. lv = pow(a, (p-1)//2, p)
  41. if lv == p - 1:
  42. lv = -1
  43. return lv
  44. def Jacobi(a, n):
  45. """Function for calculating Jacobi symbol.
  46. Note that this is only defined for positive odd integers n.
  47. Uses algorithm from
  48. <https://en.wikipedia.org/wiki/Jacobi_symbol#Calculating_the_Jacobi_symbol>
  49. """
  50. if n < 1:
  51. raise ValueError("n must be positive")
  52. if (n % 2 == 0):
  53. raise ValueError("n must be odd")
  54. if a % n != a:
  55. return Jacobi(a%n, n)
  56. if a != 0 and a % 2 == 0:
  57. nm8 = n % 8
  58. if (nm8 == 3 or nm8 == 5):
  59. return -1 * Jacobi(a//2, n)
  60. else:
  61. return Jacobi(a//2, n)
  62. if a == 1:
  63. return 1
  64. if gcd(a, n) != 1:
  65. return 0
  66. if a == 0 and n == 1:
  67. return 1
  68. if n % 4 == 3 and a % 4 == 3:
  69. return -1 * Jacobi(n, a)
  70. return Jacobi(n, a)
  71. print(" ", end=" ")
  72. for k in range(1, 10):
  73. print("{}".format(k).rjust(2, " "), end=" ")
  74. print()
  75. for n in range(1, 21, 2):
  76. print("{}:".format(n).rjust(3, " "), end=" ")
  77. for k in range(1, 10):
  78. print("{}".format(Jacobi(k, n)).rjust(2, " "), end=" ")
  79. print()