both_truncatable_primes_in_base.jl 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/julia
  2. # Author: Trizen
  3. # Date: 17 December 2023
  4. # https://github.com/trizen
  5. # Generate the entire sequence of both-truncatable primes in a given base.
  6. # Maximum value for each base is given in the following OEIS sequence:
  7. # https://oeis.org/A323137
  8. # Total number of primes that are both left-truncatable and right-truncatable in base n:
  9. # https://oeis.org/A323390
  10. # See also:
  11. # https://www.youtube.com/watch?v=azL5ehbw_24
  12. # https://en.wikipedia.org/wiki/Truncatable_prime
  13. # Related sequences:
  14. # https://oeis.org/A076586 - Total number of right truncatable primes in base n.
  15. # https://oeis.org/A076623 - Total number of left truncatable primes (without zeros) in base n.
  16. # https://oeis.org/A323390 - Total number of primes that are both left-truncatable and right-truncatable in base n.
  17. # https://oeis.org/A323396 - Irregular array read by rows, where T(n, k) is the k-th prime that is both left-truncatable and right-truncatable in base n.
  18. using Primes
  19. using Printf
  20. function is_left_truncatable(n::BigInt, base::Int64)
  21. r = big(base)
  22. while (r < n)
  23. isprime(n - r*div(n,r)) || return false
  24. r = r*base
  25. end
  26. return true
  27. end
  28. function generate_from_prefix(p::BigInt, base::Int64)
  29. seq = [p]
  30. for d in 1:base-1
  31. n = p*base + d
  32. if isprime(n)
  33. append!(seq, filter(x -> is_left_truncatable(x, base), generate_from_prefix(n, base)))
  34. end
  35. end
  36. return seq
  37. end
  38. function both_truncatable_primes_in_base(base::Int64)
  39. if (base <= 2)
  40. return []
  41. end
  42. truncatable = []
  43. for p in primes(2, base-1)
  44. append!(truncatable, generate_from_prefix(big(p), base))
  45. end
  46. return sort(truncatable)
  47. end
  48. for base in 3:36
  49. t = both_truncatable_primes_in_base(base)
  50. @printf("There are %3d both-truncatable primes in base %2d where largest is %d\n", length(t), base, last(t))
  51. end