A palindromic number or numeral palindrome is a \"symmetrical\" number like 16461, that remains the same when its digits are reversed.
The term palindromic is derive
I wrote these methods in C# which may be of some help. The main method builds a definitive list of all palindromic numbers up to the given number of digits. Its fast and commented throughout to help explain the processes I have used.
I've also included some support methods including a fast palindromic test and its worth pointing out that pow10[x] is an array of the powers of 10 to further improve speed.
lhs *= 10;
rhs /= 10;
}
palindrome = MathExt.Concat( lhs * 10, MathExt.ReverseDigits( rhs ) ); // Multiplying the lhs by 10 is equivalent to adding b == 0
result.Add( palindrome ); // Add numbers of the form aaa + 0 + aaa
lhs = a;
for ( ulong b = 1; b != 10; b++ )
{
rhs = a * 10 + b; // Adding b before we reverse guarantees that there is no trailing 0s
palindrome = MathExt.Concat( lhs, MathExt.ReverseDigits( rhs ) ); // Works except when b == 0
result.Add( palindrome ); // Add numbers of the form aaa + b + aaa
}
a++;
}
pow *= 10; // Each pass of the outer loop add an extra digit to aaa
}
return (result);
}
///
/// Reverses the digits in a number returning it as a new number. Trailing '0's will be lost.
///
/// The number to reverse.
/// The radix or base of the number to reverse.
/// The reversed number.
static public ulong ReverseDigits( ulong n, uint radix = 10 )
{
// Reverse the number
ulong result = 0;
do
{
// Extract the least significant digit using standard modular arithmetric
result *= radix;
result += n % radix;
n /= radix;
} while ( n != 0 );
return (result);
}
///
/// Concaternates the specified numbers 'a' and 'b' forming a new number 'ab'.
///
/// If a = 1234 and b = 5678 then Concat(a,b) = 12345678.
/// The first number.
/// The second number.
/// The concaternated number 'ab'.
public static ulong Concat( this ulong a, ulong b )
{
// Concaternate the two numbers by shifting 'a' to the left by the number of digits in 'b' and then adding 'b'
return (a * pow10[NumberOfDigits( b )] + b);
}
///
/// Evaluate whether the passed integer is a palindrome in base 10 or not.
///
/// Integer to test.
/// True - Palindrome, False - Non palindrome.
static public bool IsPalindrome( this ulong n )
{
uint divisor = NumberOfDigits( n ) - 1;
do
{
// Extract the most and least significant digits of (n)
ulong msd = n / pow10[divisor];
ulong lsd = n % 10;
// Check they match!
if ( msd != lsd )
return (false);
// Remove the msd and lsd from (n) and test the next most and least significant digits.
n -= msd * pow10[divisor]; // Remove msd
n /= 10; // Remove lsd
divisor -= 2; // Number has reduced in size by 2 digits
} while ( n != 0 );
return (true);
}