Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate nth n-digit palindrome efficiently?

I think the question is simple enough to understand.For more clarity I'm giving example :

In the list of 2 digit palindromes, the 7th palindrome is 77 (1st being 11, 2nd being 22 and so on).

Obviously a brute force solution exists but it's not efficient.

Can anyone suggest me some better solution to solve the problem ?

like image 361
dark_shadow Avatar asked Dec 05 '22 15:12

dark_shadow


2 Answers

First, we can simplify the problem because we only need to look at the first half of the digits (rounding up if there are an odd number of digits). I will call the first set of digits significant digits and the rest non-significant digits.

This is because the non-significant digits must match the significant digits (in reverse). It is not possible to have another palindrome number with the same leading significant digits and different non-significant digits. The significant digits determine the entire palindrome number.

Now, we just need to come up with an algorithm to generate the nth valid significant digits. This would be easier if we allowed for leading zeros, so we'll come up with the algorithm that allows for leading zeros, then tweak the algorithm.

The first few palindromes (significant digits) would be:

  • 1: 0000
  • 2: 0001
  • 3: 0002
  • ...
  • 100: 0099

So we can find the significant digits of the nth number by finding the decimal representation of (n-1).

To tweak the algorithm to work when not allowing leading zeros, we would start with a one as the leading digit:

  • 1: 1000
  • 2: 1001
  • 3: 1002
  • ...
  • 100: 1099

This boils down to finding the decimal representation of (n-1) + 1000 = n + 999 and expanding into a full palindrome:

Example: Find the 113th palindrome of length 9.

  • Determine number of digits to look at: Round up(9 / 2) = 5 --> only look at first 5 digits.
  • Find number to add to get rid of leading zeros: 10^(5-1) = 10000
  • Use formula: (113 - 1) + 10000 = 10112
  • Expanded into palindrome: 101121101

On a side note, this algorithm could also be generalized to finding the nth palindrome of any ordered set of symbols (or alphabet).

Generalized algorithm:

Given: finding palindrome number n , palindrome has m symbols as digits , there are p symbols (10 symbols in decimal)

  • Let q = ceiling(m / 2)
  • Let offset = p ^ (q - 1)
  • Let number = (n - 1) + offset
  • Let answer be number expanded as a palindrome
like image 170
ryucl0ud Avatar answered Dec 09 '22 16:12

ryucl0ud


The first few 7-digit palindrome are:

  • 1000001
  • 1001001
  • 1002001
  • 1003001
  • ...
  • 1009001
  • 1010101
  • 1011101
  • ...

I think it's very easy to see from the pattern of what is the nthm-digit palindrome...

like image 35
kennytm Avatar answered Dec 09 '22 15:12

kennytm