# Enumerate all palindromic numbers (in decimal) between 0 and n

Given a non-negative integer n, enumerate all palindromic numbers (in decimal) between 0 and n (inclusive range). A palindromic number remains the same when its digits are reversed.

The first palindromic numbers (in base 10) are given here:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, ...

This is a code golf with the prize going to fewest characters. The palindromic numbers should be output one per line to stdout. The program should read n from the commandline or stdin.

• Between 1 and n (as per title) or 0 and n (as per body)? And which of the bounds does "between" include? Aug 23 '11 at 11:45
• @wok: You still haven't answered if it's inclusive or exclusive range? Is n part of the range to include? Aug 23 '11 at 15:09
• @mellamokb Inclusive range.
– Wok
Aug 23 '11 at 15:15

## Golfscript, 15 chars

~),{.-1%~=},n*

• You may save a char comparing strings instead of numbers '~),{.-1%=},n*'. Oct 28 '12 at 9:09
• @Howard, if you want to post that yourself I'll upvote it. Oct 28 '12 at 15:32
• That would feel like plain copying ;-) Oct 29 '12 at 12:53

say for grep$_==reverse,0..<>  Needs the say feature enabled. 29 chars if you consider that to be free, otherwise 39 to add use 5.010;. Argument on STDIN. ## Perl, 35 characters #!perl -l print for grep$_==reverse,0..<>


using the old perlgolf convention that #!perl is not counted but any flags following it are.

## Perl, 36 characters

print$_,$/for grep $_==reverse,0..<>  If none of the others qualify. • Would you be so kind to explain what does$/ do? Aug 24 '11 at 8:38
• @Gurzo $/ is the input record separator, which defaults to newline. It's just a little shorter than literal "\n". Aug 24 '11 at 11:54 • Using map is shorter: map{say if$_==reverse}0..<>
– jho
Sep 1 '11 at 20:16
• @jho evil. Submit it :) Sep 1 '11 at 21:02
• If you use -E in lieu of -e, you get say for free. May 28 '12 at 20:56

## Befunge 320313 303 characters

(including significant newlines and whitespace)

 &:#v_v#  #                  :-1<
v91:<         v          <
0     >0.@    >\25**\1-:#^_v
pv   p09+1g09<^_           >$+ v :>:25*%\25*/:| ^:p18:+1g18\< : > >90g 1-:90p | > ^ >|$^     <      >-|  ^  #<
@           > 0 81p^        >:.25*,^
^                      <


I wonder if I could make this smaller by rerouting the paths...

Edit: redid the top part to avoid an extra line.

map{say if$_==reverse}0..<> Reads the argument from stdin. ## Ruby 1.9, 39 characters puts (?0..gets).select{|i|i==i.reverse}  Input (must not be terminated with a newline) via stdin. Example invocation: echo -n 500 | ruby1.9 palinenum.rb  40 characters for a version which uses commandline args: puts (?0..$*[0]).select{|i|i==i.reverse}

• Rohit proposed saving 3 characters in each of these by using p instead of puts. May 23 '12 at 9:20
• Using your code I got the following output, which seems to be wrong(I am using ruby 1.9.2p0 (2010-08-18) [i386-mingw32]) irb(main):023:0> p (?0..gets).select{|i|i==i.reverse} 1 ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "11", "22", "33", "44", "55", "66", "77", "88", " 99"] => ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "11", "22", "33", "44", "55", "66", "77", "88" , "99"]  The code below works for me p ('0'..gets[0..-2]).select{|i|i==i.reverse} Could you explain your code. May 23 '12 at 9:29
• @PeterTaylor @Rohit p and puts are not equivalent, in fact using p breaks the output, as puts writes every element on a newline, if called with an array, whereas p simply calls .to_s. May 23 '12 at 14:18

## J, 20 characters

(#~(-:|.)@":"0)>:i.n

• I can read it!:) Nice Aug 17 '12 at 8:54
• btw, to meet a requirement output numbers one per line you should add ,"0. Aug 17 '12 at 10:22
• @defhlt ,. works as well Mar 19 '18 at 17:15

## Python, 57 51 chars

for i in range(input()):
ifi==i[::-1]:print i


Usage:

echo 500 | python palindromic.py

• Shorter: for i in range(input()):ifi==i[::-1]:print i Aug 23 '11 at 14:42
• If using the interactive interpreter is legit, then you can avoid the print and just do ifi==i[::-1]:i (I say this because the Scala solution depends on this). Mar 26 '13 at 19:13
• The range should be inclusive. And i think you can change you byte count to 50 (linebreaks are shorter on linux). Nov 5 '14 at 18:04

Perl > 5.10 : 25 characters

map$_==reverse&&say,0..<>  ### APL (25 17) ↑t/⍨t≡∘⌽¨t←⍕¨0,⍳⎕  ## Javascript 122108 107 chars... I'm sure this can be golfed more - I'm new to this! n=prompt(o=[]);for(i=0;i<=n;i++)if(i+''==(i+'').split("").reverse().join(""))o.push(i);alert(o.join("\n"));  ### or n=prompt(o=[]);i=-1;while(i++<n)if(i+''==(i+'').split("").reverse().join(""))o.push(i);alert(o.join("\n"));  • Well, for starters the vars are unneeded, you can just make things global. Also prompt() doesn't strictly need parameters. Aug 23 '11 at 14:27 • However, you can use parameters to prompt() to save one semicolon: n=prompt(o=[]);. Aug 23 '11 at 15:01 • Also you still have a var i=0 that can have the var removed in your for. Aug 23 '11 at 15:02 • The trick is that i++<n compares i<n before adding 1 to i. Thus, it runs all the way to i=n. If you wanted to stop at i=n-1, you would use ++i<n instead. Aug 23 '11 at 17:21 • alert(o.join(" ")) needs to be alert(o.join("\n")) according to the specs. Add 1 to your character count when you fix this. Aug 23 '11 at 18:02 ## Perl - 43 chars for$i(0..<>){if($i==reverse$i){print$i,$/}}


This is my first attempt at code golf, so I'm pretty sure a Perl pro could golf it down.

main=do n<-readLn;mapM_ putStrLn[s|s<-map show[0..n],s==reverse s]

• Misspelled the language name... Sep 1 '11 at 16:37
• Fixed (filler chars) Sep 1 '11 at 18:03

Mathematica 61

Column@Select[0~Range~Input[],#==Reverse@#&@IntegerDigits@#&]


# Brachylog

## With the I/O format stated in the question, 8 bytes

≥ℕA↔A≜ẉ⊥


Try it online!

## With modern PPCG I/O rules, 4 bytes

≥ℕ.↔


Try it online!

This is a function that generates all the outputs, not a full program like the previous example, and so doesn't comply with the spec as written, but I thought I'd show how the program would look like if the question had been written to modern I/O standards (which permit the use of functions, and output via generators).

# Explanation

≥ℕ.↔
ℕ    Generate natural numbers
≥     less than or equal to the input
.   but output only the ones
↔  that would produce the same output if reversed


For the full program version, we create a temporary variable A to hold the output, explicitly labelize it (this is done implicitly for the main predicate of a program), and use the well-known ẉ⊥ technique for outputting a generator's elements to standard output.

• When did modern PPCG I/O rules allow you to use a generator as submission? Apr 27 '17 at 8:59
• @LeakyNun: I made the proposal on 30 Nov 2016, but the consensus is that they were already legal at that point (just not documented). We have an explicit rule allowing them now; through most of 2016, they weren't explicitly allowed and they weren't explicitly banned either.
– user62131
Apr 27 '17 at 15:35
• Oh, well, I see. Apr 27 '17 at 15:37

### Scala 59

(0 to readInt)filter(x=>""+x==(""+x).reverse)mkString("\n")

• I don't know any Scala, but does that really print on stdout? I would've guessed it's an expression returning a string.
– Omar
Nov 29 '11 at 20:58
• In the interactive scala REPL, yes. You may test it here simplyscala.com but have to replace readInt with a concrete number, online. Nov 29 '11 at 22:39

## PHP, 59 55 53 chars

for($i=0;$i++<$argv[1];)if($i==strrev($i))echo"$i\n";


Usage

php palindromic.php 500


Edit : thanks Thomas

• you can remove the {s around the for loop and remove the space in echo "$i\n" to get echo"$i\n". That'll save you a few chars. Also, if you want to be cheeky you can change \n for   and save a char. Aug 23 '11 at 16:28

## C, 98 characters

n,i,j,t;main(){for(scanf("%d",&n);i<=n;i-j?1:printf("%d ",i),i++)for(t=i,j=0;t;t/=10)j=j*10+t%10;}


{i@&{&/i=|i:$x}'i:!1+x}  # Befunge, 97 (grid size 37x4=148) #v&#:< ,*25-$#1._.@
:>:::01-\0v >-!#^_$1- *\25*/:!#v_::1>\#* #*25*#\/#$:_$\25*% -10:\<+_v#  Have a better Befunge answer to this question. This is Befunge-93 specifically; I could probably make it even more compact with Befunge-98. I'll include that in a future edit. Since you can't operate on strings in Befunge, the best I could do was compute the digit-reverse of each number (which I'm surprised I was able to manage without p and g) and compare it to the original number. The digit-reverse takes up most of the code (basically the entire third and fourth lines). Note that the program, as it stands now, prints the numbers backwards from the input down to 0. If this is a big deal, let me know. (The challenge only says to enumerate them, not specifically in increasing order.) • +1. Lines can be closed by \n alone, so it's 94 bytes long. I don't think your "grid size" has any particular relevance. Nov 7 '14 at 11:24 ## PHP, 64 58 bytes for($i=0;$i<=$argv[1];print$i==strrev($i)?$i.'\n':'',$i++)


Changed $_GET['n'] to $argv[1] for command line input.

# Jelly, 5 bytes

ŻŒḂƇY


Try it online!

• Unfortunately, this doesn't join the output list on newlines. I hope it doesn't cost any extra bytes to fix this. Feb 14 at 2:23
• @Lyxal Unsurprisingly, it does. Stupid older challenges and their crappy I/O formats Feb 14 at 2:27

# 05AB1E, 5 bytes

ƒNÂQ–


Explanation:

ƒ      # For N in range(0, input() + 1)
N     #   Push N
Â    #   Bifurcate (pushes N and N[::-1])
Q   #   Check for equality
–  #   If true, pop and print N


Uses CP-1252 encoding. Try it online!.

• LʒÂQ is 4, non-competing still though.. Oct 24 '17 at 17:49
• @MagicOctopusUrn That doesn't work, as it uses the range $1-n$, not $0-n$. Also, it outputs a list, not numbers on separate lines. Feb 8 at 16:55

# Python

n=raw_input('')
for a in range(0,int(n)+1):
r=str(a)
if str(a)==r[::-1]:
print r

• Hmm...232 characters is not really very competitive. Perhaps you could reduce the variable names to one character and delete the spaces between the variables and operators? Nov 25 '11 at 15:34
• Good job. Some good tips for golfing Python can be found in this question: codegolf.stackexchange.com/questions/54/… Nov 25 '11 at 15:48
• You can get rid of n --just replace int(n) by int(raw_input())-- and you can change str(a) to r in the if statement
– Omar
Nov 29 '11 at 20:49
• @Omar that can be golfed even more. int(raw_input()) can be just input(), the 0, in the range is unnecessary, and you can use a map to map str over the range instead of using r. Also, the print statement can be on the same line as the if statement, and indentation can be a single space. This saves a whole 38 bytes. Try it online! Feb 8 at 17:05

# Groovy, 83

System.in.eachLine{(0..it.toInteger()).each{if("$it"=="$it".reverse())println(it)}}


# Q (34 chars)

Pass n rather than n+1 as an argument for this Q solution.

{i(&)({all i=(|)i:($)x}')i:(!)1+x}  # Q,32 {a(&)a~'((|:)')a:((-3!)')(!)1+x}  ## Q (33) {if[x="I"$(|:) -3!x;:x]} each til


Probably a neater way to do this but anyway, sample usage (you enter n+1 to get to n):

q){if[x="I"$(|:) -3!x;:x]} each til 10 0 1 2 3 4 5 6 7 8 9  Suggestion by tmartin, gets it down to 29: ({$[x="I"$(|:) -3!x;x;]}')(!)  Same usage. ## Python, 106 characters import sys as a print(type(a.argv[1])) for x in range(int(a.argv[1])+1): x=str(x) if x==x[::-1]:print(x)  usage: python a.py 500  • 82 bytes Feb 15 at 22:45 # C# (217214 191 chars) Golfed version: using System;using System.Linq;class P{static void Main(){int n=int.Parse(Console.ReadLine());do{var t=(n+"").ToArray();Array.Reverse(t);Console.Write(n+""==new string(t)?n+"\n":"");}while(n-->0);Console.ReadLine();}}  Readable: using System; using System.Linq; class P { static void Main() { int n = int.Parse(Console.ReadLine()); do { var t = (n + "").ToArray(); Array.Reverse(t); Console.Write(n + "" == new string(t) ? n + "\n" : ""); } while (n-->0); Console.ReadLine(); } }  This prints out palindromes in descending order making use of the n-->0 operator. (as n goes to 0). *Edited version replaces do...while with while, saving 3 chars, but now you must input with n+1. using System;using System.Linq;class P{static void Main(){int n=int.Parse(Console.ReadLine());while(n-->0){var t=(n+"").ToArray();Array.Reverse(t);Console.Write(n+""==new string(t)?n+"\n":"");}Console.ReadLine();}}  *edited: found a better way to reverse string without converting to array: using System;using System.Linq;class P{static void Main(){int n=int.Parse(Console.ReadLine());while(n-->0)Console.Write(n+""==string.Join("",(""+n).Reverse())?n+"\n":"");Console.ReadLine();}}  Readable: using System; using System.Linq; class P { static void Main() { int n = int.Parse(Console.ReadLine()); while (n-->0) Console.Write(n + "" == string.Join("", ("" + n).Reverse()) ? n + "\n" : ""); Console.ReadLine(); } }  # PHP 53 Can 53 be any lower? Four different options: for($i=$argv[1];$i-->0;)echo$i==strrev($i)?"$i\n":""; for($i=$argv[1];$i-->0;)if($i==strrev($i))echo"$i\n"; while(($i=$argv[1]--)>0)echo$i==strrev($i)?"$i\n":"";
while(($i=$argv[1]--)>0)if($i==strrev($i))echo"$i\n";  If you want to get funky... PHP 47 while(($i=$argv[1]--)>0)if($i==strrev($i))$i;
`

You have to ignore the error text. The palindrome numbers are still output to the command line, however.