Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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

Output

the palindrome reached.

share|improve this question
@Nakilon please give a reason for your edit. – Eelvex Jan 29 '11 at 8:31
1  
Because your question is probably the only one involving the 196 algorithm. Making single-use tags is not useful. – Chris Jester-Young Jan 29 '11 at 8:48
1  
@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 ;) – Eelvex Jan 29 '11 at 9:49
1  
@GigaWatt also, I had missread your fist question :) Just don't bother with A023108s' case. – Eelvex Mar 9 '12 at 16:03
1  
@Joel, as with A023108, just ignore them (act like you don't know about them); we don't know if any exists anyway. – Eelvex May 27 '12 at 15:02
show 7 more comments

19 Answers

up vote 6 down vote accepted

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
share|improve this answer
It saves a few characters to use numeric input. {⍵=A←⍎⌽⍕⍵:⍵⋄∇A+⍵}⎕. You save the braces, a reverse and an eval. – marinus May 27 '12 at 7:38

Python 56

Following JPvdMerwe suggestion:

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

Python 62:

n=raw_input()
while n!=n[::-1]:n=`int(n)+int(n[::-1])`
print n
share|improve this answer
Hehe ..)))))))) – Nakilon Jan 28 '11 at 21:53
2  
By looking at n as an int you can shorten by 6 characters, check for the code: meta.codegolf.stackexchange.com/q/75/62 – JPvdMerwe 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. – JPvdMerwe Jan 29 '11 at 18:56

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).
share|improve this answer
3  
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? ;-) – Chris Jester-Young 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 – Chris Jester-Young Jan 29 '11 at 4:33
Your family is worried about you – user11 Jan 29 '11 at 4:36
show 1 more comment

Ruby — 56 chars

x,r=gets
x="#{x.to_i+r.to_i}"until x==r=x.reverse
puts x
share|improve this answer

J 25 27 31

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

Python: 66

n=input()
while 1:
 r=int(`n`[::-1])
 if n==r:break
 n+=r
print n
share|improve this answer

Perl, 40 chars

$_=<>;$_+=$r while$_!=($r=reverse);print
share|improve this answer

PHP - 54 48 characters

<?for($s=`cat`;$s!=$r=strrev($s);$s+=$r);echo$s;

Test:

$ php 196.php <<< 5280
23232
share|improve this answer
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]. – GigaWatt Mar 8 '12 at 23:01
@GigaWatt: $s='m4' should also work. – ninjalj Nov 23 '12 at 20:49

Scala 82

def p(n:Int):Int={val s=n.toString.reverse.toInt
if(n==s)n else p(n+s)}
p(readInt)
share|improve this answer

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
share|improve this answer
r=input()
while 1:
    r=`r`
    if r==r[::-1]:
      break
    else:
      r=int(r)+int(r[::-1])

print r
share|improve this answer

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)

share|improve this answer
The task description states that only the final palindrome should be printed. – Joey Jan 29 '11 at 12:00

Windows PowerShell (63)

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.

share|improve this answer
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.

share|improve this answer
1  
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((==)%)((+)%) – hammar Nov 8 '11 at 21:47

Bash (64)

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

Call with: bash <filename> <number>

share|improve this answer
What is the <filename> for? – Eelvex Mar 9 '12 at 5:50
@Eelvex the script needs to call itself so you need to store it in a file. – marinus 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.

share|improve this answer

befunge, 57 bytes

"KCTS"4(&:0\v
\T\a*+\:0`jv>: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.
share|improve this answer

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;
}
share|improve this answer

I am new to Java and I am not sure if my idea it will work, but I am gonna try to do it next week. I hope I will have time to try it, it seems so fun ;) my idea is : 1 - make copy of the input number.
2 - convert the copy of input number to string. 3 - use the bubble sort to revers the whole string "chars". 4 - return it to a number and then add it to the original number. 5 - do it again.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.