Palindrome Reversal-Addition
Python, 51
def f(n):r=int(str(n)[::-1]);return n-r and-~f(n+r)
For Python 2, backticks can't replace str()
because of the L
attached to long
literals.
Here's an alternate version with score 64 * 0.85 = 54.4:
def f(n,c=262):r=int(str(n)[::-1]);return c*(n-r)and-~f(n+r,c-1)
And an alternate version for Python 3 with score 88 * 0.6 = 52.8:
def f(n,c=262):r=int(str(n)[::-1]);return c*(n-r)and-~f(n+r,print(n,'+',r,'=',n+r)or~-c)
Pyth, 12 bytes
f_I`~+Qs_`Q0
Try it online: Demonstration or Test harness
This uses a quite new feature (only 17 hours old).
Explanation
implicit: Q = input number
f 0 repeat the following expression until it
evaluates to true and return the number of steps
`Q convert Q to string
_ reverse the digits
s convert to int
+Q add Q
~ assign the result to Q
(this returns the old value of Q)
` convert the old value of Q to a string
_I and check if it's invariant under the operation reverse
edit:
Changed the code a little bit. The old version was
fqKs_`Q~+QK0
Same byte count, but the new one is way cooler.
CJam, 23 22 20.4 bytes
ri{__sW%i+}261*]{s_W%=}#
The code is 24 bytes long and prints -1 for Lychrel candidates.
Try it online.
How it works
ri e# Read an integer from STDIN.
{ }261* e# Do the following 261 times:
__ e# Push two copies of the integer on the stack.
sW%i e# Cast to string, reverse and cast back to integer.
+ e# Add the copy and the reversed copy of the integer.
] e# Wrap all 262 results in an array.
{ }# e# Push the index of the first element such that:
s e# The string representation equals...
_W%= e# the reversed string representation.
If {}#
is successful, the index is also the number of steps. If, on the other hand, the array does not contain a palindrome, {}#
will push -1.