6

consider that

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

what is an efficient algorithm to find the nth palindromic number?

Merna
  • 269
  • 1
  • 5
  • 14

2 Answers2

13

I'm assuming that 0110 is not a palindrome, as it is 110.

I could spend a lot of words on describing, but this table should be enough:

#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...
Sjoerd
  • 6,837
  • 31
  • 44
0

The (nonzero) palindromes with even number of digits start at p(11) = 11, p(110) = 1001, p(1100) = 100'001,.... They are constructed by taking the index n - 10^L, where L=floor(log10(n)), and append the reversal of this number: p(1101) = 101|101, p(1102) = 102|201, ..., p(1999) = 999|999, etc. This case must be considered for indices n >= 1.1*10^L but n < 2*10^L.

When n >= 2*10^L, we get the palindromes with odd number of digits, which start with p(2) = 1, p(20) = 101, p(200) = 10001 etc., and can be constructed the same way, using again n - 10^L with L=floor(log10(n)), and appending the reversal of that number, now without its last digit: p(21) = 11|1, p(22) = 12|1, ..., p(99) = 89|8, ....

When n < 1.1*10^L, subtract 1 from L to be in the correct setting with n >= 2*10^L for the case of an odd number of digits.

This yields the simple algorithm:

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] ))
       }

where [...] is 1 if ... is true, 0 else, and \ is integer division. (The expression n \ 10^[...] is equivalent to: if ... then n\10 else n.)

(I added the condition n > 1 in the exponent to avoid P = 10^(-1) for n=0. If you use integer types, you don't need this. Another choice it to put max(...,0) as exponent in P, or use if n=1 then return(0) right at the start. Also notice that you don't need L after assigning P, so you could use the same variable for both.)

mastisa
  • 1,875
  • 3
  • 21
  • 39
Max
  • 415
  • 5
  • 12