2
$\begingroup$

OEIS A002113, palindromes in base 10, shows a number of Mathematica constructs. I have used:

pals = {0}; r = 2; Do[
 Do[AppendTo[pals, 
   n*10^(IntegerLength[n] - 1) + 
    FromDigits@Rest@Reverse@IntegerDigits[n]], {n, 10^(e - 1), 10^e - 1}];
 Do[AppendTo[pals, 
   n*10^IntegerLength[n] + FromDigits@Reverse@IntegerDigits[n]], {n, 
   10^(e - 1), 10^e - 1}], {e, r}]; pals

... with r = 7 but going up to r = 8 would take too long. Might there be a way to recode this so that r = 8 can be accomplished in a reasonable amount of time? I'm prepared to do weeks, but not months.

$\endgroup$
3
  • 1
    $\begingroup$ It is very likely that using ParallelDo on a computer with 4 or more processors/cores is going to put you in the "waiting for weeks" time-frame. $\endgroup$ Feb 17, 2020 at 18:33
  • 1
    $\begingroup$ What is r? Number of digits? $\endgroup$
    – MikeY
    Feb 17, 2020 at 19:02
  • $\begingroup$ Using a specific integer r will generate a list of all palindromes less than 10^(2r). So, for r=2, up to 9999; for r=3, up to 999999. $\endgroup$ Feb 17, 2020 at 19:47

2 Answers 2

3
$\begingroup$
palindromeNdigits[n_Integer?Positive]:=
  Tuples[Array[Boole[#==1]~Range~9&,⌈n/2⌉,Boole[n!=1]]][[;;,Array[Min[#,n+1-#]&,n]]
  ].(10^Range[0,n-1]);

palindromeGen[max_Integer?NonNegative]:=
  Join@@Array[palindromeNdigits,Max[Ceiling@Log10@max,1]]//Pick[#,UnitStep[max-#],1]&;

palindromeNdigits[2]

{11, 22, 33, 44, 55, 66, 77, 88, 99}

palindromeGen[500]

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99,
101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232,
242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373,
383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494}

palindromeGen[10^10] // Total // AbsoluteTiming

{0.0257969, 545045045045040}

$\endgroup$
1
  • $\begingroup$ I ran palindromeGen[10^18] on a recently acquired 2020 iMac i9 and it created the two billion (less one) terms in 493 seconds! $\endgroup$ Apr 28, 2022 at 15:40
5
$\begingroup$

Every positive integer with two digits $\{a,b\}$ generates the palindromes $\{a,b,b,a\}$ and $\{a,b,a\}$. This generalizes to more than two digits.

PalindromeGen[max_] :=
   Block[{d, n, lim},
      lim = If[max < 11, 10, Ceiling[10^(1/2 + Ceiling[Log[10, max]]/2)]];
      Sort@Pick[d = Flatten[
        Table[
           d = IntegerDigits[n];
           {FromDigits[Join[d, Reverse[d]]], 
            FromDigits[Join[d, Rest[Reverse[d]]]]},
        {n, 1, lim}]],
        UnitStep[max - d], 1]]

For example,

AbsoluteTiming[Total[PalindromeGen[10^10]]]

{1.29566, 545045045045040}

An upper limit of $10^{12}$ took about 13s, corresponding to your $r=6$. An upper limit of $10^{14}$ took 133s.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.