count_of_palindromic_numbers.sf 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/usr/bin/ruby
  2. # Algorithm from https://oeis.org/A137180
  3. # Based on work by Eric A. Schmidt and Robert G. Wilson v.
  4. # Extended to any base >= 2 by Daniel Șuteu (June 06 2021).
  5. # See also:
  6. # https://oeis.org/A002113 -- Palindromes to base 10.
  7. # https://oeis.org/A050250 -- Number of nonzero palindromes less than 10^n.
  8. # https://oeis.org/A027383 -- Number of palindromes (in base 2) below 2^n.
  9. # https://oeis.org/A117862 -- Number of palindromes (in base 3) below 3^n.
  10. # https://oeis.org/A117863 -- Number of palindromes (in base 4) below 4^n.
  11. # https://oeis.org/A117864 -- Number of palindromes (in base 5) below 5^n.
  12. # Explicit formula for the number of palindromes <= 10^n for base = 10 (due to Bruno Berselli, Feb 15 2011):
  13. # (1/2)*10^((2*n + (-1)^n - 1)/4)*(13 - 9*(-1)^n) - 2
  14. func nth_palindrome(n, b=10) {
  15. var p = 1
  16. (n-1).times { p.next_palindrome!(b) }
  17. return p
  18. }
  19. func palindrome_count(n, b=10) {
  20. return 0 if (n < 1)
  21. var q = floor(n * b**-(idiv(1+n.ilog(b), 2)))
  22. var r = (q + b**(q.ilog(b) + (n.ilog(b)%2)) - 1)
  23. r + floor(tanh(n - nth_palindrome(r, b)))
  24. }
  25. for b in (2..10) {
  26. say ("Number of base-#{b} palindromes <= 10^n: ", 7.of {|n| palindrome_count(10**n, b) })
  27. }
  28. __END__
  29. Number of base-2 palindromes <= 10^n: [1, 5, 19, 61, 204, 644, 2000, 6535, 20397, 63283]
  30. Number of base-3 palindromes <= 10^n: [1, 5, 19, 62, 202, 652, 2099, 6759, 21802, 70488]
  31. Number of base-4 palindromes <= 10^n: [1, 5, 20, 76, 218, 646, 2000, 6537, 22485, 77417]
  32. Number of base-5 palindromes <= 10^n: [1, 5, 23, 63, 203, 783, 2223, 6323, 22023, 79623]
  33. Number of base-6 palindromes <= 10^n: [1, 6, 21, 62, 260, 677, 2066, 9010, 20634, 68089]
  34. Number of base-7 palindromes <= 10^n: [1, 7, 20, 67, 251, 632, 2816, 6565, 22754, 76304]
  35. Number of base-8 palindromes <= 10^n: [1, 8, 19, 77, 218, 705, 2463, 6537, 28508, 63283]
  36. Number of base-9 palindromes <= 10^n: [1, 9, 19, 92, 203, 864, 2098, 8083, 21802, 75982]
  37. Number of base-10 palindromes <= 10^n: [1, 9, 18, 108, 198, 1098, 1998, 10998, 19998, 109998]