# 196 algorithm code golf

Write a short program for 196-algorithm. The algorithm starts from an integer, then adds its reverse to it until a palindrome is reached.

e.g.

input = 5280
5280 + 0825 = 6105
6105 + 5016 = 11121
11121 + 12111 = 23232
output = 23232


Input

an integer, which is not a lyrchrel number (that is, it does eventually yield a palindrome under this algorithm, rather than continuing infinitely)

Output

the palindrome reached.

• Because your question is probably the only one involving the 196 algorithm. Making single-use tags is not useful. Jan 29 '11 at 8:48
• What I meant was, your question is likely to be the only one ever to involve this topic, even in 2 years' time. :-) Jan 29 '11 at 9:12
• @Chris: Well, 196-algorithm is a pretty popular one, going by many different names. Just to be sure, though, I'll post another question about it before the 2-year-time lapses ;) Jan 29 '11 at 9:49
• @GigaWatt also, I had missread your fist question :) Just don't bother with A023108s' case. Mar 9 '12 at 16:03
• @Joel, as with A023108, just ignore them (act like you don't know about them); we don't know if any exists anyway. May 27 '12 at 15:02

## APL (22 characters)

{a≡⌽a←⍕(⍎⍵)+⍎⌽⍵:a⋄∇a}⍞


This works in Dyalog APL. Here's an explanation, from right to left:

• { ... }⍞: Get input from the user as characters (⍞) and feed it to our function ({ ... }).
• Within the direct function (⋄ separates statements, so we look at them from left to right):
• a≡⌽a←⍕(⍎⍵)+⍎⌽⍵ : a: Evaluate (⍎) the right argument's (⍵) reverse (⌽), and add that to the evaluated version of the right argument itself. Then, format the result (⍕; i.e., give its character representation), assign (←) that to the variable a, and finally test if a's reverse is equivalent to a (i.e., is a a palindrome?). If true, return a; otherwise...
• ∇a: Feed a back into our function (∇ is implicit self-reference).

Example:

      {a≡⌽a←⍕(⍎⍵)+⍎⌽⍵:a⋄∇a}⍞
412371
585585

• It saves a few characters to use numeric input. {⍵=A←⍎⌽⍕⍵:⍵⋄∇A+⍵}⎕. You save the braces, a reverse and an eval. May 27 '12 at 7:38

## GolfScript, 29 chars

~]{{..-1%.@={;0}{~+1}if}do}%


Selected commentary

The meat of the program is the do loop, of course. So I'll just cover that.

1. . copies the number and stringifies it.
2. .-1% copies that string version and reverses it.
3. .@ copies the reversed version, and brings the original non-reversed version to the front.

So, say, the number is 5280. At this stage, the stack is: 5280 "0825" "0825" "5280". The stage is set for the comparison. (After the comparison, the stack will be left at 5280 "0825" no matter what---the items to compare have been popped off.)

1. If the string and the reverse are the same, we don't care about the reversed string, so just pop it off (;) and return 0 (to end the do loop).
2. If they don't match, then evaluate (~) the reversed string (to make it a number), add (+) that to the original number, and return 1 (to continue the do loop).
• Are you sure you didn't press random keys on your keyboard? It looks like that...
– user11
Jan 29 '11 at 3:03
• @M28: GolfScript looks even more like line noise than Perl, doesn't it? ;-) Jan 29 '11 at 3:10
• I feel sorry for you, it must be painful to code that
– user11
Jan 29 '11 at 3:51
• @M28: That wasn't nearly as painful as the solution I wrote for Luhn algorithm. Just think about that. :-P Jan 29 '11 at 4:33
– user11
Jan 29 '11 at 4:36

# Python 2, 55 bytes

Following JPvdMerwe suggestion:

n=input()
whilen!=n[::-1]:n+=int(n[::-1])
print n


Python 2, 62:

n=raw_input()
while n!=n[::-1]:n=int(n)+int(n[::-1])
print n

• Hehe ..)))))))) Jan 28 '11 at 21:53
• By looking at n as an int you can shorten by 6 characters, check for the code: meta.codegolf.stackexchange.com/q/75/62 Jan 28 '11 at 22:39
• Seems I accidentally included the new line vim sneakily added to the end of my file to my count. The real count is 55. Jan 29 '11 at 18:56

Ruby — 56 chars

x,r=gets
x="#{x.to_i+r.to_i}"until x==r=x.reverse
puts x


Just exercising my Pyth skills, not a serious contender.

# Pyth, 16 bytes

L?bqb_by+vbi_bTyz


Equivalent to Python 3:

y=lambda b:b if b==b[::-1] else y(str(eval(b)+int(b[::-1],10)))
print y(input())

• Just trying some old challenges, already answered, so not serious contender. Dec 23 '14 at 19:28
• Some challenge authors will update the accepted answer if a shorter solutions comes in, so I think it's fair to inform the OP, that this is not technically a valid submission. (Don't get me wrong, I like to answer old challenges with CJam for fun, too - and I just did a few minutes ago. I'm just saying, if you do, leave a note, that the language is newer than the challenge.) Dec 23 '14 at 19:30
• Actually being "not a serious contender" makes an answer subject to deletion -- but I don't see any reason this shouldn't be considered a serious contender. Aug 29 '19 at 4:02

# J 25 27 31

f=:(+g)^:(~:g=.|.&.":)^:_
e.g.
f 5280
23232


# CJam, 22 21 bytes

CJam was created after this question was asked, so technically its an invalid submission. But I found the question interesting, so here goes:

r{__W%:X=0{~X~+s1}?}g


Explanation:

r{                 }g    "Read the input number as string and enter a while-do loop";
__                     "Make 2 copies of the string number";
W%:X                 "Reverse the second and store it in X";
=                "Check if the number is already palindrome";
0{      }?      "Put 0 on stack if it is palindrome, else, run the code block";
~             "Convert the string to int";
X~           "Put the reverse string on stack and convert it to int too";
+s         "Add the two numbers and covert back the result to string";


The core logic is that in each while-do iteration, you first check if palindrome is achieved or not. If not, add the reverse to the number. Pretty much what the algorithm is!

Try it online here

This is an actual contender, since J has been around for decades.

# J (16 bytes)

(+^:~:|.&.":)^:_


This is a verb, so it can be assigned to a variable in a J session and used like so:

   f =. (+^:~:|.&.":)^:_
f 5280
23232


How it works:

(+^:~:|.&.":)^:_
|.&.":     reverse under string format
+^:~:|.&.":     add reverse unless a palindrome
(           )^:_ repeat until unchanged


# 05AB1E, 7 bytes

Code:

[DÂQ#Â+


Explanation:

[        # Infinite loop.
DÂ      # Duplicate and bifurcate (which duplicates it and reverses the duplicate).
Q#    # If the number and the number reversed are equal, break.
Â+  # Add the reversed number to the initial number.


Uses the CP-1252 encoding. Try it online!.

• Could you explain a little more on the process of bifurcation? Jul 28 '16 at 18:41
• @CᴏɴᴏʀO'Bʀɪᴇɴ For example, on the stack is the string hello. The bifurcation will keep the original string, and pushes the string reversed. It's short for duplicate and reverse. Jul 28 '16 at 18:43
• Oh, I see. Cool! Thanks Jul 28 '16 at 18:51

Python: 66

n=input()
while 1:
r=int(n[::-1])
if n==r:break
n+=r
print n


Perl, 40 chars

$_=<>;$_+=$r while$_!=($r=reverse);print  • I know this is a really old post but a few changes can reduce this to 26 bytes: Try it online! Aug 1 '18 at 9:34 ### Scala 82 def p(n:Int):Int={val s=n.toString.reverse.toInt if(n==s)n else p(n+s)} p(readInt)  # JAGL Alpha 1.2 - 19, 21 with stdin Not contending, just getting some experience with my language Expects a number from stdin T~d{DddgCi+dgdC=n}uSP  Explanation T~ Get a line of input, and eval to an integer d Duplicate (for first round) {Ddd Drop last and duplicate twice gCi Convert to string, reverse, and convert back to integer +d Add to original and duplicate gdC Convert to string, duplicate, reverse =n} If it isn't a palindrome, keep going uSP Run until palindrome reached, then print output number  • Edited. @Optimizer Dec 24 '14 at 6:47 • Please don't edit all your submissions at once for minor edits (like a version number), as this unnecessarily clutters the front page. It's fine if you do 2 or maybe 3 at a time, but please wait a few hours before doing more systematic edits. Dec 30 '14 at 0:51 • Forgot that it would push to front page, my bad. @MartinBüttner Dec 30 '14 at 0:52 # Brachylog, 8 bytes ↔?|↔;?+↰  Try it online! Somewhat similar to one of the first Brachylog programs I saw and was intrigued by, from the Brachylog introduction video. ?↔?.|↔;?+↰. (initial ? and the .s are implicit) ?↔? % If the input and its reverse are the same, . % then the input is the output |↔;?+↰ % Or, add the input and its reverse, and call this predicate recursively . % The result of that is the output  # PHP - 54 48 characters <?for($s=cat;$s!=$r=strrev($s);$s+=$r);echo$s;


Test:

$php 196.php <<< 5280 23232  • I'm going to have to remember the $str = cat thing for future golfing. Heck of a lot better than using STDIN and still better than $argv[0]. Mar 8 '12 at 23:01 • @GigaWatt:$s='m4' should also work. Nov 23 '12 at 20:49

## Bash (64)

X=rev<<<$1|sed s/^0*//;[$1 = $X ]&&echo$1||. $0$(($1+$X))


Call with: bash <filename> <number>

• What is the <filename> for? Mar 9 '12 at 5:50
• @Eelvex the script needs to call itself so you need to store it in a file. Mar 12 '12 at 14:52

## C# - 103 99 chars

public int P(int i)
{
var r = int.Parse(new string(i.ToString().Reverse().ToArray())));
return r == i ? i : P(i + r);
}


C# never does very well in golf. Elegant, but verbose.

• You can easily golf it more. Use ""+ rather than .ToString and get rid of some spaces. Dec 30 '14 at 4:46

## In Q (39 characters)

f:{while[x<>g:"I"$reverse -3!x;x+:g];x}  Sample Usage: q)f 5280 23232  Edit: Down to 34 now, same usage: {while[x<>g:"I"$(|) -3!x;x+:g];x} 5280

r=input()
while 1:
r=r
if r==r[::-1]:
break
else:
r=int(r)+int(r[::-1])

print r

• Please leave what language you used and how many bytes it has; although I recognized it written in Python 2. Jul 20 at 8:35

# Jelly, 9 bytes (non competing)

A very simple answer, just for the challenge of coding in and esoteric language.

ṚḌ+µŒḂ¬$¿ ṚḌ : take the argument, reverse (and vectorize) it +µ : add both ŒḂ¬$¿ : while the result isn't a palindrome


Try it online!

Should this answer be unclear or wrong on any level, feel free to point it out.

Thanks to Dennis for helping me out with this first small piece of code.

• Wow, not everyone uses Jelly in their first post. Apr 25 '18 at 14:36
• It was on my to-do list to post an answer on PPCG using an esoteric language. Jelly happened to be the first one I thought of :)
– z3r0
Apr 25 '18 at 14:40

# Java (JDK), 78 71 bytes

i->{for(int r=0,t;i!=r;)for(t=i+=r,r=0;t>0;t/=10)r=r*10+t%10;return i;}


Try it online!

-7 Thanks to Celingcat!

• Welcome to Code Golf! Nice first answer. Aug 17 at 12:41
• Thanks :D A friend showed me code.golf and I've been loving it since. first submission on this forum. Aug 17 at 12:43

Python. 85 characters:

s,i=str,int;rs=lambda q:s(q)[::-1];n=i(input());
while rs(n)!=s(n):n+=i(rs(n));print n


If you don't want output on each iteration:

s,i=str,int;rs=lambda q:s(q)[::-1];n=i(input());
while rs(n)!=s(n):n+=i(rs(n))
print n


(one less character)

• The task description states that only the final palindrome should be printed.
– Joey
Jan 29 '11 at 12:00

for($a=+"$input";-join"$a"[99..0]-ne$a){$a+=-join"$a"[99..0]}$a  I still hate it that there is no easy way to reverse a string. • Can be shortened by two characters if there only ever are ten digits of input. This way it's safe for long as well which is the largest integral type PowerShell supports anyway but still, I waste two chars. – Joey Jan 29 '11 at 11:56 Haskell 89 87 chars r=read.reverse.show main=getLine>>=print.head.filter(\x->x==r x).iterate(\x->x+r x).read  Somewhat readable version: myFind p = head . filter p rev = read . reverse . show isPalindrome x = x == rev x next x = x + rev x sequence196 = iterate next palindrome196 = myFind isPalindrome . sequence196 main = getLine >>= print . palindrome196 . read  The golfed version was created by manual inlining and renaming the remaining functions to single character names. • You can shorten this quite a bit by taking advantage of the underused function until from the Prelude, as well as extracting the pattern of applying a binary operator to x and r x. Also, use readLn instead of getLine and read. The result saves 20 characters: f%x=f x$read.reverse.show$x;main=readLn>>=print.until((==)%)((+)%) Nov 8 '11 at 21:47 • @hammar: You could use the function monad and save even more: Define r=(=<<read.reverse.show) and just use r(==)untilr(+). Apart from that saving, it doesn't need to be a full program, a valid submission could just be the unnamed function from before. This brings you down to 41 bytes: Try it online! Aug 2 '18 at 18:31 ## befunge, 57 bytes "KCTS"4(&:0\v \T\a*+\:0jv>:a%\a/ 0:+_v#-TD2$<^\
@.<


though the code is places in a 4x19 grid, so might call it 76.

• first line is initializeing, and reading input number
• second line reverse first number in stack and put it in the second stack position.
• and the third line checks if a number is palindrome.

## C++ TMP (256 characters)

#include<cstdio>
#define Y(A,B,C,D)template<int N>struct A<C,D>{enum{v=B};};
#define Z(A)template<int N,int M>struct A{enum{v=
#define n 5194
Z(R)R<N/10,M*10+N%10>::v};};Y(R,N,0,N)Z(S)S<N+M,R<N+M,0>::v>::v};};Y(S,N,N,N)main(){printf("%d",S<n+R<n,0>::v,0>::v);}


This version could be shortened a bit, but a 256-character answer is hard to pass up. Here's an un-golfed version:

#include <iostream>

template<size_t N>
class Reverse
{
template<size_t M, size_t R>
struct Inner
{
enum { value = Inner<M/10, R*10 + M%10>::value };
};

template<size_t R>
struct Inner<0, R>
{
enum { value = R };
};

public:
enum { value = Inner<N, 0>::value };
};

template<size_t N>
class OneNineSix
{
template<size_t M, size_t R=Reverse<M>::value>
struct Inner
{
enum { value = OneNineSix<M + R>::value };
};

template<size_t M>
struct Inner<M, M>
{
enum { value = M };
};

public:
enum { value = Inner<N + Reverse<N>::value>::value };
};

int main()
{
const size_t N = 4123;

std::cout << OneNineSix<N>::value << std::endl;
}


## Pyke, 13 bytes (noncompeting)

D_b]D$XIsr)h  Try it here!  _b - int(reversed(str(num)) D ] - [num, ^] D - _ = ^$       -  delta(^)
XI     - if ^:
s    -  num = sum(_)
r   -  goto_start()
h - _[0]


L,BDbRBv
D,f,@,1]A+
D,g,@,1]A=
D,h,@,{f}A{g}Q{h}
L,{h}2/i


Try it online!

## How it works

L,	; Create a function 'lambda 1'
; Example argument:   [5280]
BD	; Digits;     STACK = [[5 2 8 0]]
bR	; Reverse;    STACK = [[0 8 2 5]]
Bv	; Undigits;   STACK = [825]

D,f,@,	; Define a monadic function 'f'
; Example argument:         [5280]
1]	; Call 'lambda 1';  STACK = [825]
A+	; Add the argument; STACK = [6105]

D,g,@,	; Define a monadic function 'g'
; Example argument:          [5280]
1]	; Call 'lambda 1';   STACK = [825]
A=	; Equal to argument; STACK = [0]

D,h,@,	; Define a monadic function 'h'
; Example argument:  [5280]
{f}	; Call 'f';  STACK = [6105]
A{g}	; If 'g'...
Q	;   Return
{h}	; Else call 'h'

L,	; Define a function, 'lambda 2'
; Example argument: [5280]
{h}	; Call 'h'; STACK = [46464]
2/i	; Halve;    STACK = [23232]


# C (gcc), 132 bytes

t;r(char*s){char*e=s+strlen(s)-1;for(;e>s;*e--=*s,*s++=t)t=*e;}g(o,l,f){for(l=malloc(9);sprintf(l,"%d",o),r(l),f=atoi(l),f-o;)o+=f;}


Call with g(n) for an int n. Try it online here.

Ungolfed:

t; // temporary varaiable fpr swapping characters
r(char *s) { // helper function to reverse a string: takes a string argument and modifies it
char *e = s + strlen(s) - 1; // find the end of the string
for(; e > s; // move the end pointer and the start pointer towards each other until they meet
*e-- = *s, *s++ = t) // swap the characters under the start and end pointers ...
t = *e; // ... using the temporary variable
}
g(o, // function for the 196 algorithm: takes an int argument and returns an int
l, f) { // abusing the argument list to declare to extra variables: one is a string for reversing the number, the other is an int
for(l = malloc(9); // allocate space for the string
sprintf(l, "%d", o), // convert the number to a string
r(l), // reverse that string
f = atoi(l), // convert it back to an int
f - o; ) // loop until the two numbers are equal
o += f; // add the two numbers
}

• 119 bytes Oct 2 '18 at 3:48

# Powershell, 63 62 bytes

param($m)for(;$m-$s;$m=-join"$s"[-1..-"$s".Length]){$s+=$m};$s  Test script: $f = {
param($m)for(;$m-$s;$m=-join"$s"[-1..-"$s".Length]){$s+=$m};$s } &$f 5280

• You don't need the ; between param(\$m) and for. Aug 3 '18 at 14:01