is_both_truncatable_prime.sf 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 16 January 2018
  4. # https://github.com/trizen
  5. # Check if a given number is left-truncatable and right-truncatable in a given base.
  6. # Maximum value for each base is given in the following OEIS sequence:
  7. # https://oeis.org/A323137
  8. # See also:
  9. # https://www.youtube.com/watch?v=azL5ehbw_24
  10. # https://en.wikipedia.org/wiki/Truncatable_prime
  11. # Left-truncatable primes in base 10:
  12. # https://oeis.org/A024785
  13. # Right-truncatable primes in base 10:
  14. # https://oeis.org/A024770
  15. # Other related sequences:
  16. # https://oeis.org/A076586 - Total number of right truncatable primes in base n.
  17. # https://oeis.org/A076623 - Total number of left truncatable primes (without zeros) in base n.
  18. # https://oeis.org/A323390 - Total number of primes that are both left-truncatable and right-truncatable in base n.
  19. # 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.
  20. func is_left_truncatable_prime(n, base) {
  21. var digits = n.digits(base)
  22. while (digits) {
  23. digits[-1] || return false
  24. is_prime(digits2num(digits, base)) || return false
  25. digits.first!(-1)
  26. }
  27. return true
  28. }
  29. func is_right_truncatable_prime(n, base) {
  30. var digits = n.digits(base)
  31. while (digits) {
  32. is_prime(digits2num(digits, base)) || return false
  33. digits.last!(-1)
  34. }
  35. return true
  36. }
  37. func is_both_truncatable(n, base) {
  38. is_left_truncatable_prime(n, base) &&
  39. is_right_truncatable_prime(n, base)
  40. }
  41. say is_both_truncatable(21335388527, 30) #=> true
  42. say is_both_truncatable(1591175082967, 64) #=> true
  43. say is_both_truncatable(1272571820725769, 42) #=> true
  44. say is_both_truncatable(200416308070405393, 60) #=> true
  45. say { is_left_truncatable_prime(_, 10) }.first(20) #=> [2, 3, 5, 7, 13, 17, 23, 37, 43, 47, 53, 67, 73, 83, 97, 113, 137, 167, 173, 197]
  46. say { is_right_truncatable_prime(_, 10) }.first(20) #=> [2, 3, 5, 7, 23, 29, 31, 37, 53, 59, 71, 73, 79, 233, 239, 293, 311, 313, 317, 373]