Generating Numeric Palindromes.

7k Views Asked by At

I have just started the Euler project, and felt like I didn't get the fourth problem right...I used string conversion to test if my numbers were symmetrical, instead of relying on (the much faster) method of mathematically producing palindromes.

I have searched more than a dozen times on variations of this subject, and have found every last approach to this problem (computationally) involves translating the number from base 2 to base 10, so that it can be manipulated in a more human-friendly way.

Is there a pattern, or function that exists to generate palindromic numbers?

2

There are 2 best solutions below

0
On BEST ANSWER

Mathematically producing palindromes is not necessarily faster than using strings.

2
On

For a six digit palindrome (as in Project Euler problem 4), you can take an integer $n$ with $100 \le n \le 999$ and calculate

$$1100 \times n - 990 \times \lfloor n/10 \rfloor - 99 \times \lfloor n/100 \rfloor$$

and palindromes with other numbers of digits can be generated a similar way.

For example with $n=317$ you get $1100 \times 317 - 990 \times 31 - 99 \times 3 = 317713$.