Program: Number Palindromes
My wife, Betty, recently reminded me of a theorem that I must have studied in high school but whose name I have long since forgotten: that any positive integer number can be used to generate a palindrome by adding to it the number comprised of its digits in reverse order. Palindromes are sequences that read the same in either direction, such as the name “Anna” or the phrase “Madam, I’m Adam” (being non-strict and ignoring spaces and punctuation). We normally think of palindromes as composed of text, but the concept can be applied to numbers: 13531 is a palindrome. Start with the number 72, for example, and add to it the number 27. The results of this addition is 99, which is a (short) palindrome. Starting with 142, add 241, and you get 383. Some numbers take more than one try to generate a palindrome. 1951 + 1591 yields 3542, which is not palindromic. The second round, however, 3542 + 2453, yields 5995, which is. The number 17,892, which my son Benjamin picked out of the air, requires 12 rounds to generate a palindrome, but it does terminate:
C:\javasrc\numbers>java Palindrome 72 142 1951 17892 Trying 72 72->99 Trying 142 142->383 Trying 1951 Trying 3542 1951->5995 Trying 17892 Trying 47763 Trying 84537 Trying 158085 Trying 738936 Trying 1378773 Trying 5157504 Trying 9215019 Trying 18320148 Trying 102422529 Trying 1027646730 Trying 1404113931 17892->2797227972 C:\javasrc\numbers>
If this sounds to you like a natural candidate for recursion, you are ...