next_palindrome_in_base.pl 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/perl
  2. # A nice algorithm, due to David A. Corneth (Jun 06 2014), for generating the next palindrome from a given palindrome.
  3. # Generalized to other bases by Daniel Suteu (Sep 16 2019).
  4. # See also:
  5. # https://oeis.org/A002113
  6. # https://en.wikipedia.org/wiki/Palindromic_number
  7. use 5.020;
  8. use strict;
  9. use warnings;
  10. use ntheory qw(:all);
  11. use experimental qw(signatures);
  12. sub next_palindrome ($n, $base = 10) {
  13. my @d = todigits($n, $base);
  14. my $l = $#d;
  15. my $i = ((scalar(@d) + 1) >> 1) - 1;
  16. while ($i >= 0 and $d[$i] == $base - 1) {
  17. $d[$i] = 0;
  18. $d[$l - $i] = 0;
  19. $i--;
  20. }
  21. if ($i >= 0) {
  22. $d[$i]++;
  23. $d[$l - $i] = $d[$i];
  24. }
  25. else {
  26. @d = (0) x (scalar(@d) + 1);
  27. $d[0] = 1;
  28. $d[-1] = 1;
  29. }
  30. fromdigits(\@d, $base);
  31. }
  32. foreach my $base (2 .. 12) {
  33. my @a = do {
  34. my $n = 1;
  35. map { $n = next_palindrome($n, $base) } 1 .. 20;
  36. };
  37. say "base = $base -> [@a]";
  38. }
  39. __END__
  40. base = 2 -> [3 5 7 9 15 17 21 27 31 33 45 51 63 65 73 85 93 99 107 119]
  41. base = 3 -> [2 4 8 10 13 16 20 23 26 28 40 52 56 68 80 82 91 100 112 121]
  42. base = 4 -> [2 3 5 10 15 17 21 25 29 34 38 42 46 51 55 59 63 65 85 105]
  43. base = 5 -> [2 3 4 6 12 18 24 26 31 36 41 46 52 57 62 67 72 78 83 88]
  44. base = 6 -> [2 3 4 5 7 14 21 28 35 37 43 49 55 61 67 74 80 86 92 98]
  45. base = 7 -> [2 3 4 5 6 8 16 24 32 40 48 50 57 64 71 78 85 92 100 107]
  46. base = 8 -> [2 3 4 5 6 7 9 18 27 36 45 54 63 65 73 81 89 97 105 113]
  47. base = 9 -> [2 3 4 5 6 7 8 10 20 30 40 50 60 70 80 82 91 100 109 118]
  48. base = 10 -> [2 3 4 5 6 7 8 9 11 22 33 44 55 66 77 88 99 101 111 121]
  49. base = 11 -> [2 3 4 5 6 7 8 9 10 12 24 36 48 60 72 84 96 108 120 122]
  50. base = 12 -> [2 3 4 5 6 7 8 9 10 11 13 26 39 52 65 78 91 104 117 130]