需要算法来找到第n个回文数

need algorithm to find the nth palindromic number

本文关键字:回文 算法      更新时间:2023-10-16

考虑

    0 -- is the first
    1 -- is the second
    2 -- is the third
    .....
    9 -- is the 10th
    11 -- is the 11th

找到第n个回文数的有效算法是什么?

我假设0110不是回文,因为它是110。

我可以花很多词来描述,但这张表应该足够了:

#Digits #Pal. Notes
   0     1     "0" only
   1     9     x     with x = 1..9
   2     9     xx    with x = 1..9
   3    90     xyx   with xy = 10..99 (in other words: x = 1..9, y = 0..9)
   4    90     xyyx  with xy = 10..99
   5   900     xyzyx with xyz = 100..999
   6   900     and so on...

偶数位数的(非零)回文从p(11) = 11, p(110) = 1001, p(1100) = 100'001,...开始。它们是通过取索引n - 10^L来构造的,其中L=floor(log10(n)),并附加此数字的反转:p(1101) = 101|101, p(1102) = 102|201, ..., p(1999) = 999|999, etc。对于索引n >= 1.1*10^L but n < 2*10^L,必须考虑这种情况。

n >= 2*10^L时,我们得到了奇数位数的回文,它们以p(2) = 1, p(20) = 101, p(200) = 10001 etc.开始,可以用同样的方式构造,再次使用n - 10^L with L=floor(log10(n)),并附加该数字的反转,现在没有最后一个数字p(21) = 11|1, p(22) = 12|1, ..., p(99) = 89|8, ...

n < 1.1*10^L时,在奇数位数的情况下,用n >= 2*10^L从L中减去1以达到正确设置。

这就产生了一个简单的算法:

p(n) = { L = logint(n,10);
         P = 10^(L - [1 < n < 1.1*10^L]); /* avoid exponent -1 for n=1 */
         n -= P; 
         RETURN( n * 10^L + reverse( n  10^[n >= P] ))
       }

其中[…]是1如果。。。为true,否则为0,\为整数除法。(表达式n 10^[...]等效于:if ... then n10 else n。)

(我在指数中添加了条件n>1,以避免n=0时p=10^(-1)。如果您使用整数类型,则不需要它。另一种选择是将max(…,0)作为P中的指数,或者在开始时使用if n=1 then return(0)。还要注意,在分配P之后不需要L,所以可以对两者使用相同的变量。)