title: Draw an ASCII chess board!

text:
# Question
Title: Draw an ASCII chess board!
Here is a simple challenge for you: You must produce this ASCII representation of a chess board. White is represented by uppercase characters, and black is represented by lowercase. Empty tiles are represented by a `.`. Here is the full board:

```
rnbqkbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKBNR

```

Since this is a question, you may not take any input and you must output this board by any default method, for example, saving a file, printing to STDOUT or returning from a function. You *may* optionally produce one trailing newline. Standard loopholes apply, and the shortest program in bytes!

However, remember this is equally as much a competition between submissions in the same language. While it's unlikely that a languages like Java could beat a language like perl, or a golfing language like pyth or cjam, having the shortest Java answer is still really impressive! To help you track the shortest answer in each language, you may use this leaderboard, which will show the shortest submission by language and overall.

## Leaderboards

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=95745,OVERRIDE_USER=31716;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 21 votes
# Vim, 26 bytes

`irnbqkbnr<Esc>Y6p5Vr.VrpYGPgUj`

Relies on a fresh Vim, or else `5V` may select the wrong area.

* `irnbqkbnr<Esc>`: Write the top row. Easy enough.
* `Y6p`: Make the rest of the rows, *except one*. Of course all but the top and bottom rows contain the wrong characters.
* `5Vr.`: When you haven't used visual mode yet in the session, you can do things like this to select 5 lines. If you typed the same thing again right away, it would try to select 25 lines. Vim is weird like that.
* `Vrp`: We're already on line 2, so let's make a pawn line.
* `YGP`: Copy that pawn line into its place at the bottom. This is why I used `6p` instead of `7p` before.
* `gUj`: Capitalize the white pieces.

# Answer
> 17 votes
# Jelly, ~~25~~ 24 bytes

```
“.“.“p“rnbqkbn”ṁ€8µṚ;ŒuY

```

Try it online!

*Thanks to @Lynn for golfing off 1 byte!*

### How it works

```
“.“.“p“rnbqkbn”ṁ€8µṚ;ŒuY  Main link. No arguments.

“.“.“p“rnbqkbn”           Yield [".", ".", "p", "rnbqkbnr"].
               ṁ€8        Mold-each 8; reshape each string like the array
                          [1, 2, 3, 4, 5, 6, 7, 8], i.e., cyclically repeat its
                          contents to create strings of length 8.
                          This yields the upper half of the board in reversed
                          order, i.e., the string array
                          A := "........", "........", "pppppppp", "rnbqkbnr"].
                  µ       Begin a new, monadic chain. Argument: A
                   Ṛ      Reverse A.
                     Œu   Convert all characters in A to uppercase.
                    ;     Concatenate the results to both sides.
                       Y  Join the strings, separating by linefeeds.

```

# Answer
> 13 votes
# Brainfuck, 224 bytes

```
+++++[>+++[>++++++<-]+<-]>>.[>>+>+<<<-]>>>[<<<+>>>-]<<<----.<+++[>---<-]>.>>-.------.<<.>>+++.++++.--<++++++++++>>++++++++++.<........>.[>+++++<-]>----<++++[>........<<<.>>-]<........<.>++.----.<<.>>+++.------.<<.>>+++.++++.

```

Took almost an hour to get this.

# Answer
> 9 votes
## Python 2, 63 bytes

```
print"\n".join(["rnbqkbnr","p"*8]+["."*8]*4+["P"*8,"RNBQKBNR"])

```

Unfortunately, the fairly simple approach was much shorter than the "clever" stuff I tried at first...

Bonus answer, also 63 bytes:

```
print"\n".join(["rnbqkbnr"]+[c*8for c in"p....P"]+["RNBQKBNR"])

```

# Answer
> 9 votes
# 05AB1E, 24 bytes

Uses CP-1252 encoding.

```
"rnbqkbnr"'p8×'.8×D)Âu«»

```

Try it online!

**Explanation**

```
"rnbqkbnr"                # push the string "rnbqkbnr"
                          # STACK: "rnbqkbnr"
          'p8×            # push the char "p" repeated 8 times
                          # STACK: "rnbqkbnr", "pppppppp"
              '.8×        # push the char "." repeated 8 times
                          # STACK: "rnbqkbnr", "pppppppp", "........"
                  D       # duplicate
                          # STACK: "rnbqkbnr", "pppppppp", "........", "........"
                   )      # wrap in list
                          # STACK: ["rnbqkbnr", "pppppppp", "........", "........"]
                    Â     # push a reversed copy of the list
                          # STACK: ["rnbqkbnr", "pppppppp", "........", "........"],
                                   ["........", "........", "pppppppp", "rnbqkbnr"]
                     u«   # convert to upper-case and concatenate
                          # STACK: ['rnbqkbnr', 'pppppppp', '........', '........',
                                    '........', '........', 'PPPPPPPP', 'RNBQKBNR']
                       »  # join list by newline

```

# Answer
> 7 votes
# Actually, 26 bytes

```
'p8*"rnbqkbnr"│û@û4'.8*n((

```

Try it online!

Explanation:

```
'p8*"rnbqkbnr"│û@û4'.8*n((
'p8*                        "p"*8 ["pppppppp"]
    "rnbqkbnr"              that string ["rnbqkbnr", "pppppppp"]
              │             duplicate stack ["rnbqkbnr", "pppppppp", "rnbqkbnr", "pppppppp"]
                û@û         uppercase the dupes ["RNBQKBNR", "PPPPPPPP", "rnbqkbnr", "pppppppp"]
               4   '.8*n    "."*8, 4 times ["RNBQKBNR", "PPPPPPPP", "........", "........", "........", "........", "rnbqkbnr", "pppppppp"]
                        ((  move the uppercase strings to the bottom of the stack, implicitly print

```

# Answer
> 7 votes
# Ruby, ~~45~~ 44

1 byte saved thanks to tuxcrafting.

```
puts"rnbqkbnr",?p*8,[?.*8]*4,?P*8,"RNBQKBNR"

```

This is 45

```
puts s="rnbqkbnr",?p*8,[?.*8]*4,?P*8,s.upcase

```

Trying anything cleverer just seems to make it longer.

# Answer
> 7 votes
## JavaScript (ES6), ~~69~~ 65 bytes

*Saved 4 bytes thanks to edc65*

```
let f =

_=>`rnbqkbnr
p....PRNBQKBNR`.replace(/p|\./ig,c=>c.repeat(8)+`
`)

console.log(f());
```

# Answer
> 7 votes
## PowerShell v2+, 44 bytes

```
'rnbqknbr'
'p'*8
,('.'*8)*4
'P'*8
'RNBQKNBR'

```

Strings left on the pipeline are implicitly printed with `Write-Output` at program execution. We couple that with the default newline behavior for an array to produce the four lines of periods with the comma-operator.

```
PS C:\Tools\Scripts\golfing> .\draw-ascii-chess-board.ps1
rnbqknbr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKNBR

```

# Answer
> 6 votes
# Cheddar, 56 bytes

```
a=['rnbqkbnr','p'*8]+['.'*8]*2->(a+a.rev=>@.upper).vfuse

```

Uses the new `=>` feature.

## Explanation

```
a=                      // set a to the first half
  ['rnbqkbnr','p'*8] +  // First two rows
  ['.'*8]*2             // Next two dots
->(
   a +
   a.rev=>@.upper       // Reverse and map all items to uppercase
).vfuse                 // Join on newlines

```

# Answer
> 6 votes
# C#, 94 92 bytes

*Edit: Thanks to milk for saving 1 byte by changing string order to remove the return whitespace.*

*Edit: Saved 1 more byte by adding a dummy parameter (**x** instead of **()**) for the anonymous function and calling it with any object.*

```
x=>{string a="RNBQKBNR\n",b="PPPPPPPP\n",c="........\n";return(a+b).ToLower()+c+c+c+c+b+a;};

```

Full program using the above function:

```
using System;

namespace DrawAnASCIIChessBoard
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<object,string>f= x=>{string a="RNBQKBNR\n",b="PPPPPPPP\n",c="........\n";return(a+b).ToLower()+c+c+c+c+b+a;};
            Console.WriteLine(f(1));
        }
    }
}

```

C# is a very verbose language...

---

# C# full program, 131 bytes

```
class P{static void Main(){string a="rnbqkbnr\n",b="pppppppp\n",c="........\n";System.Console.Write(a+b+c+c+c+c+(b+a).ToUpper());}}

```

Ungolfed:

```
class P
{
    static void Main()
    {
        string a="rnbqkbnr\n",
            b="pppppppp\n",
            c="........\n";
        System.Console.Write(a+b+c+c+c+c+(b+a).ToUpper());
    }
}

```

# Answer
> 6 votes
## Pyke, ~~28~~ ~~27~~ 26 bytes

```
"rnbqkbnr"i"P..p"1c8m*Xil3

```

Try it here!

I learned something new about my language today: `1c` can be used as a 2 char way of splitting a string into a list of characters.

```
"rnbqkbnr"i                - i = "rnbqkbnr"
                             stack = ["rnbqkbnr"])
           "P..p"1c        -  chunk("P..p", 1)
                             stack = ["rnbqkbnr", ["P", ".", ".", "p"]]
                   8m*     - map(8*>, ^)
                             stack = ["rnbqkbnr", ["PPPPPPPP", "........", "........", "pppppppp"]]
                      X    - splat(^)
                             stack = ["rnbqkbnr", "pppppppp", "........", "........", "PPPPPPPP"]
                       il3 - i.changecase()
                             stack = ["rnbqkbnr", "pppppppp", "........", "........", "PPPPPPPP", "RNBQKBNR"]
                           - implicit join with newlines

rnbqkbnr
pppppppp
........
........
PPPPPPPP
RNBQKBNR

```

# Answer
> 6 votes
# Commodore BASIC V2/V7 (Commodore C64/128, VIC-20, TheC64Mini) - 129 tokenized and BASIC bytes

```
 0n$=cH(13):a$="{clear}{ctrl+h}{ctrl+n}rnbqkbnr"+n$:p$="pppppppp"+n$:?a$p$;:fOi=0to3:?"........":nE:goS1:?p$a$:end
 1a$="RNBQKBNR"+n$:p$="PPPPPPPP"+n$:reT

```

This should be entered into BASIC on a Commodore 128 and saved, it will then load into the VIC/C64 okay (you may need `LOAD "CHESS",8,0` on the VIC-20), or use CBM PRG Studio. The reason for this is that I'm going over the 80/88 character limit in line `0` for the C64/VIC-20 respectively. The C128 allows a 160 PETSCII character limit, so with keyword abbreviations this could easily be \> 160 character per BASIC line.

The `{clear}` character is achieved by `SHIFT` \+ `CLR/HOME`, whereas (in a string) `CTRL+H` disables the `SHIFT+C=` key to toggle between graphics and business mode, and `CTRL+N` changes the case to business mode in BASIC.

The resulting listing is as in the screen shot. Copy the listing above and paste it into `WinVICE` with a right-click on your mouse over the `VICE` window.

I've added the resulting output on the VIC-20 to prove that it'll load on that mighty micro as well.

# Answer
> 5 votes
## Haskell, 53 bytes

```
a="rnbkqbnr"
unlines$a:map(<$a)"p....P"++["RNBKQBNR"]

```

`a` is used as the first line and to determine the length of strings made of `p`, `.` and `P` (-\> `<$a`). .

# Answer
> 5 votes
# MATL, 26 bytes

```
'rnbqkbnr' 'p..'!l8X"vtPXk

```

Try it online!

### Explanation

```
'rnbqkbnr'   % Push this string (1×8 char array)
'p..'!       % Push this string transposed (3×1 char array)
l8X"         % Repeat 1×8 times: gives 3×8 char array
v            % Concatenate the two arrays vertically into a 4×8 char array
tP           % Duplicate and flip vertically
Xk           % Convert to uppercase. Implicitly display the two 4×8 arrays

```

# Answer
> 5 votes
# , 34 bytes

```
(tolower,|.)4 8$'RNBQKBNR',8#'P..'

```

Try it online!

# Answer
> 5 votes
# Ex, ~~66~~ 61 bytes

(not a language per se, but reproductible line-oriented editor)

```
a
rnbqkbnr
.
t.
%t.
%t.
2s/./p/g
7s/./P/g
8s/./\u&/g
3,6s/././g
x

```

Second version, shorter, and sure there's room for improvement while staying POSIX.

```
a
rnbqkbnr
.
t.
%t.
%t.
2,7s/./p/g
7,8s/./\u&/g
3,6s/././g
x

```

## usage notes

To try online, just launch `ex yourfilename` then paste the lines. The result will be viewable with `cat yourfilename`.

## ungolfed/explanation

It's a line oriented editor (which will serve our purpose here as we operate line by line), with commands following the general syntax "line/range command parameters" (so 3 colomns plus one for comment following)

```
    a         " append following lines until line with dot only
rnbqkbnr
.
    t .       " duplicate current line
              "rnbqkbnr
              "rnbqkbnr
%   t .       " duplicate the whole buffer (2 lines)
              "rnbqkbnr
              "rnbqkbnr
              "rnbqkbnr
              "rnbqkbnr
%   t .       " copy the whole buffer (4 lines)
              "rnbqkbnr
              "rnbqkbnr
              "rnbqkbnr
              "rnbqkbnr
              "rnbqkbnr
              "rnbqkbnr
              "rnbqkbnr
              "rnbqkbnr
2,7 s/./p/g   " from line 2 to 7, replace each character with lower P
              "rnbqkbnr
              "pppppppp
              "pppppppp
              "pppppppp
              "pppppppp
              "pppppppp
              "pppppppp
              "rnbqkbnr
7,8 s/./\u&/g " on lines 7 and 8, replace each character with its uppercase
              "rnbqkbnr
              "pppppppp
              "pppppppp
              "pppppppp
              "pppppppp
              "pppppppp
              "PPPPPPPP
              "RNBQKBNR
3,6 s/././g   " from line 3 to 6, replace each character with a dot
              "rnbqkbnr
              "pppppppp
              "........
              "........
              "........
              "........
              "PPPPPPPP
              "RNBQKBNR
    x         " write the buffer into file and close the editor

```

Commands have a full name and a shortcut used here, as we're golfing.

* `a` for `append`, to switch into input mode until a sole dot
* `s` for `substitute`, with parameters /RegExp/replacement/flags where the flag `g` here means all occurrences (instead of default first only)
* `t` initialy means *transfer* and is put for `copy` (the letter C was already used to *change*/replace line) with as parameter the line after one should copy (and the `.` is for the current)
* `x` for `xit` and is put for *exit* (the letter E was already used to *edit* a file)

That's all.

# Answer
> 4 votes
# , ~~27~~, 26 bytes

```
i¸P
RNBQKBNRäkgujddppÒ.4Ä

```

Try it online!

This contains some unprintable characters, so here is the readable version:

```
i¸P
RNBQKBNR<esc>äkgujddppÒ.4Ä

```

where `<esc>` represents `0x1B`. Explanation:

```
i                               " Enter insert mode
 ¸P                             " Enter 8 'P' characters
                                " and a newline
RNBQKBNR<esc>                   " Enter the first row and escape to normal mode.
             äk                 " Duplicate this line and the line above
               guj              " Convert this line, and the line below to lowercase
                  dd            " Delete this line
                    pp          " And paste it twice below us
                      Ò.        " Replace this whole line with '.' chars
                        4Ä      " And create four copies of this line

```

# Answer
> 4 votes
# Python 2, 68 bytes

Posting anyway although the above Python 2 version is shorter. It would not have to be a one liner for the amount of bytes, just played with it.

```
x,y,z="rnbqkbnr\n","p"*8+"\n","."*8+"\n";print x,y,4*z,(y+x).upper()

```

# Answer
> 4 votes
# JavaScript (ES6), 73

`.toUpperCase` is simply too long

```
_=>`rnbqkbnr
${r=c=>c[0].repeat(8)+`
`,r`p`+(b=r`.`)+b+b+b+r`P`}RNBQKBNR`

```

```
O.textContent=(

_=>`rnbqkbnr
${r=c=>c[0].repeat(8)+`
`,r`p`+(b=r`.`)+b+b+b+r`P`}RNBQKBNR`

)()
```

```
<pre id=O></pre>
```

# Answer
> 4 votes
# Emotinomicon, 89 bytes

Sadly Emotinomicon has nothing like an duplicate stack function. Would be usefull. But at least shorter than Java. :)

```
RNBKQBNR
PPPPPPPP
........
........
........
........
pppppppp
rnbkqbnr⏪⏬⏩

```

Explanation:

```
(...)⏪⏬⏩
(...)            String literal
         ⏪  ⏩      Loop
           ⏬        Pop one char and output

```

# Answer
> 4 votes
## Python 3.5, 56 bytes

```
for r in['rnbqkbn',*'p....P','RNBQKBN']:print((r*8)[:8])

```

This uses an idea by zawata to encode each line as `(r*8)[:8]`, with a string repeated 8 times and trimmed to length `8`. The pawns and empty rows are just `'p'*8`, `'.'*8`, and `'P'*8`, with no trimming. The first row uses `'rnbqkbn'`, with `('rnbqkbn'*8)[:8]` including another rook on the right when multiplied and trimmed. The last row is the same but capitalized.

We express the list of row-parts compactly `['rnbqkbn','p','.','.','.','.','P','RNBQKBN']` using Python 3.5's generalized unpacking. We write out the first and last-entries, and the remaining single-character ones are unpacked from a string.

In Python 2, we could settle for `split` instead for 60 bytes:

```
for i in'rnbqkbn p . . . . P RNBQKBN'.split():print(i*8)[:8]

```

# Answer
> 4 votes
# C, 87 bytes

```
#define E "........\n"
main(){puts("rnbqkbnr\npppppppp\n"E E E E"PPPPPPPP\nRNBQKBNR");}

```

This uses preprocessor and string literal joining. Sorry, Matthew Greci and CSM, I don't have any reputation here to comment on your solution

# Answer
> 4 votes
## Python 3, 59 bytes

```
print('rnbqkbnr','p'*8,*['.'*8]*4,'P'*8,'RNBQKBNR',sep='\n')

```

Interesting that with better unpacking and print function, Python 3 can be much better than Python 2 for golf

This was based on https://codegolf.stackexchange.com/a/95758/2212

# Answer
> 4 votes
# Vyxal `J`, <sup>~~26 24 31 28~~</sup> 25 bytes

-2 bytes thanks to the `j` flag.
+7 bytes, added code to swap Q and K to make it valid.
-3 bytes thanks to Aaron Miller!
-3 bytes thanks to Kevin Cruijssen

```
«æ≠⁺tO«\p8*\.8*:W⁋Ḃ⇧‛KQḂV

```

## Explanation

```
«æ≠⁺tO«                         - Push "rnbqkbnr"
       \p8*                     - Push "pppppppp"
           \.8*:                - Push "........" twice
                W⁋              - Listify, then join by \n
                  Ḃ⇧            - Bifurcate and uppercase the second half
                    ‛KQḂV       - Replace "KQ" with "QK"
<flag>                          - Join by newlines and print entire stack implicitly

```

Try it Online!

# Answer
> 3 votes
# Powershell, ~~82~~ 73 bytes

```
$x=("rnbqkbnr",$("p"*8),$("."*8),$("."*8));$x+$x[3..0].ToUpper()-join"`n"

```

# Answer
> 3 votes
# GNU sed, 54 bytes

```
s:^:rnbqkbnr:p;h
s:.:p:gp;G
h;s:[^\n]:.:gp;G
s:.:\U&:g

```

**Try it online!**

**Explanation:**

The black pieces are printed first, saving the two associated board ranks in reverse order in the hold space. The white pieces are printed by converting the hold space to uppercase letters.

```
s:^:rnbqkbnr:p;h   # change pattern and hold spaces to 'rnbqkbnr' and print string
s:.:p:gp           # replace each pattern space letter with a 'p', then print
G;h                # append hold space, then copy pattern space to hold space
s:[^\n]:.:gp       # replace each pattern space letter with a '.', then print
G;s:.:\U&:g        # append hold space and convert pattern space to uppercase
                   # (automatic printing of pattern space at the end)

```

# Answer
> 3 votes
# Brain-Flak, ~~366~~ 350 + 3 = 353 bytes

Try it online!

```
(((((((((((()()())){}(((({}))){}{}(([((({})){}){}](([({}())](((((({}()){}){}){}()){})<>))<>)<>)<>)))<<>({}<>)<>({}<>)<>({}<>)([]()())>[()]))))))))(()()()()){({}[()]<((((((((((((()()()()()){})()){}()){}))))))))>)}{}(((()()()()()){})<((((((((([][]()()()()))))))))<>)<>>)(((((()()()))){})(({}{})(([{}({})](([{}()](<>({}()())<>)<>)<>)<>)<>))){<>({}<>)}{}

```

This gets a plus 3 because it requires the `-A` flag to run properly.

## Explanation

```
First we push the last 5 letters to the active stack.
We also push copies of last 3 numbers to the inactive stack.
This is done with fairly simple methods I won't go into for the sake of brevity.

 (((()()())){}(((({}))){}{}(([((({})){}){}](([({}())](((((({}()){}){}){}()){})<>)<><>)<>)<>)<>)))

We Move Everything from the offstack to the onstack.
The first 3 letters are the same as the last 3 letters in the first line

{<>({}<>)}{}

We push 10 for a new line

((()()()()()){})

Using the value of Q we create a P and push it 8 times

((((((((<...>[()]))))))))

We loop 4 times each time pushing 8 dots and a newline

(()()()())
{({}[()]<
    ((((((((((((()()()()()){})()){}()){}))))))))
>)}{}

We push the last two lines in a very similar way to the first two.

(((()()()()()){})<((((((((([][]()()()()))))))))<>)<>>)(((()()()){})(({}()()())(([{}(()()())](([{}()](<>({}()())<>)<>)<>)<>)<>))){<>({}<>)}{}

```

# Answer
> 3 votes
# Python 3, 82 80 75 Bytes

Not the shortest answer in python but it's my first and i think its pretty good for a first time

```
print('\n'.join((i*8)[:8]for i in'rnbqkbn p . . . . P RNBQKBN'.split()))

```

# Answer
> 3 votes
# C, ~~112~~ 109

```
char *e="rnbqkbnr";main(a){for(;a<65;)putchar((a++-1)%9?a<11?e[a-3]:a<20?112:a<48?46:a<57?80:e[a-57]-32:13);}

```

---

Readable:

```
char *e="rnbqkbnr";
main(a){
    for(;a<65;)
        putchar((a++-1)%9?a<11?e[a-3]:a<20?112:a<48?46:a<57?80:e[a-57]-32:13);
}

```

Notes:
•char 13 = new line
•char 112 = 'p'
•char 46 = '.'
•char 80 = 'P'
•lowercase char-32 = UPPERCASE CHAR

Thoughts: It's annoying because this is very well golfed for a short solution, but at the same time I could have gone sub-100 in my byte count by just hard coding in most of the chess board and just repeating the `.` `.` `.` part with a puts loop. But that's a very boring answer

---

Thanks @Ahemone for 3 bytes off!

# Answer
> 3 votes
# x86-64 Machine Code, 81 bytes

```
57                   push        rdi
48 BA 52 4E 42 4B 51 42 4E 52 mov         rdx,524E42514B424E52h
52                   push        rdx
BA 50 50 50 50       mov         edx,50505050h
52                   push        rdx
89 54 24 04          mov         dword ptr [rsp+4],edx
51                   push        rcx
5A                   pop         rdx
6A 30                push        30h
59                   pop         rcx
48 2B E1             sub         rsp,rcx
54                   push        rsp
5F                   pop         rdi
B0 2E                mov         al,2Eh
F3 AA                rep stos    byte ptr [rdi]
0F 10 44 24 30       movups      xmm0,xmmword ptr [rsp+30h]
0F 11 04 24          movups      xmmword ptr [rsp],xmm0
54                   push        rsp
52                   push        rdx
56                   push        rsi
5A                   pop         rdx
5F                   pop         rdi
5E                   pop         rsi
B1 10                mov         cl,10h

80 74 8C FF 20       xor         byte ptr [rsp+rcx*4-1],20h
E2 F9                loop        addLoop (07FF66A5A13B8h)
B1 08                mov         cl,8
B0 0A                mov         al,0Ah

48 A5                movs        qword ptr [rdi],qword ptr [rsi]
AA                   stos        byte ptr [rdi]
E2 FB                loop        addLoop+0Bh (07FF66A5A13C3h)
C6 07 00             mov         byte ptr [rdi],0
48 83 C4 40          add         rsp,40h
48 8B F2             mov         rsi,rdx
5F                   pop         rdi
C3                   ret

```

Create using abuse of push/pop instructions. Could probably save a few bytes by using Linux calling conventions. Outputs to a pointer specified in the first parameter `rcx`.

# Answer
> 3 votes
# Vyxal `L`, 17 bytes

```
«æ≠⁺tO«ƛ`p..`+Ḃ⇧+

```

Try it Online!

-1 thqnks to Aaron Miller.

```
«...«           # Compressed string `rnbqkbnr`
     ƛ          # Map...
      `p..`+    # Append `p..` to each
            Ḃ   # Duplicate, reverse
             ⇧+ # Uppercase the reversed copy and append
                # (L flag) vertical join (rotate 90°) at the end.

```

# Answer
> 3 votes
# (gcc), ~~71~~ 70 bytes

I would be really surprised if someone could make this any shorter (seems impossible to me, but who knows?).

**Edit**: The cat has one-upped me again.

```
*c=L"湲煢扫牮瀊灰灰灰ੰ⸮⸮⸮⸮⸊⸮⸮⸮ਮ⸮⸮⸮⸮⸊⸮⸮⸮ਮ偐偐偐偐刊䉎䭑乂ꁒ";main(){for(;printf(c++););}

```

Try it online (with explanation)

**Explanation**:

```
// The full output stored as wide characters.
// Each wide character stores 2 ASCII characters (represented as U+XXYY).
// For example, to store "rn" take the ASCII values (r => 0x72, n => 0x6E) and
// find the character U+6E72. Notice the order is reversed. I assume this is
// because x86 is little-endian.
*c=L"湲煢扫牮瀊灰灰灰ੰ⸮⸮⸮⸮⸊⸮⸮⸮ਮ⸮⸮⸮⸮⸊⸮⸮⸮ਮ偐偐偐偐刊䉎䭑乂ꁒ";
main(){
    // printf() returns the number of characters printed. When 'c' contains
    // '\0' at the end of the string, printf() will return 0. Resulting in
    // the loop terminating.
    for(;printf(c++););
}

```

# Answer
> 2 votes
# J, ~~55~~ 52 bytes

```
'.rnbkqpPQKBNR'{~(+-@|.)8 8$1 2 3 4 5 3 2 1,8 48#6 0

```

## Test and intermediate steps

```
   '.rnbkqpPQKBNR'{~(+-@|.)8 8$1 2 3 4 5 3 2 1,8 48#6 0
rnbkqbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBKQBNR
   8 48#6 0
6 6 6 6 6 6 6 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
   1 2 3 4 5 3 2 1,8 48#6 0
1 2 3 4 5 3 2 1 6 6 6 6 6 6 6 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
   8 8$1 2 3 4 5 3 2 1,8 48#6 0
1 2 3 4 5 3 2 1
6 6 6 6 6 6 6 6
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
   (+-@|.)8 8$1 2 3 4 5 3 2 1,8 48#6 0
 1  2  3  4  5  3  2  1
 6  6  6  6  6  6  6  6
 0  0  0  0  0  0  0  0
 0  0  0  0  0  0  0  0
 0  0  0  0  0  0  0  0
 0  0  0  0  0  0  0  0
_6 _6 _6 _6 _6 _6 _6 _6
_1 _2 _3 _4 _5 _3 _2 _1
   '.rnbkqpPQKBNR'{~(+-@|.)8 8$1 2 3 4 5 3 2 1,8 48#6 0
rnbkqbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBKQBNR

```

# Answer
> 2 votes
# Gloo, 46 Bytes

Gloo is a very, erm, *young* language with very little stack manipulation implemented. I think this is probably the best I can do since there's also no uppercase function. The raw bytes are below, and can be run from the interpreter using `gloo.py -f <file>`.

```
Offset   00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
000000   22 72 6E 62 71 6B 62 6E 72 0A 22 22 70 22 38 2A   "rnbqkbnr.""p"8*
000010   22 0A 22 22 2E 22 38 2A 22 0A 22 2B 34 2A 22 50   ".""."8*"."+4*"P
000020   22 38 2A 22 0A 52 4E 42 51 4B 42 4E 52 22         "8*".RNBQKBNR"

```

---

This doesn't count because it was updated after the challenge started, but now there's an easy 32 byte solution:

`"rnbqkbnr"'p8*[_?¶Ä'.4*‘8*’;[¶jj`

```
Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000  22 72 6E 62 71 6B 62 6E 72 22 27 70 38 2A 5B 5F  "rnbqkbnr"'p8*[_
00000010  3F B6 C4 27 2E 34 2A 91 38 2A 92 3B 5B B6 6A 6A  ?¶Ä'.4*‘8*’;[¶jj

```

# Answer
> 2 votes
## R, 75 bytes

Edit: Fixed a silly error and simply write out the uppercase part of the board now.

```
cat("rnbqkbnr\npppppppp\n",rep("........\n",4),"PPPPPPPP\nRNBQKBNR",sep="")

```

# Answer
> 2 votes
# IBM/Lotus Notes Formula, 69 bytes

```
A:="rnbqkbnr";B:="pppppppp";C:="........";A:B:C:C:C:C:@Uppercase(B:A)

```

Formula in a multi-value field with newline as the seperator.

Output:

# Answer
> 2 votes
## Batch, 105 bytes

```
@set e=@echo ........
@echo rnbqkbnr
@echo pppppppp
%e%
%e%
%e%
%e%
@echo PPPPPPPP
@echo RNBQKBNR

```

Batch is seriously verbose...

# Answer
> 2 votes
# ///, 52 bytes

```
/:/........
/rnbqkbnr
pppppppp
::::PPPPPPPP
RNBQKBNR

```

Try it online!

# Answer
> 2 votes
# Java 7, ~~103~~ ~~99~~ 89 bytes

```
String f(){return"rnbqkbnr\npppppppp\nxxxxPPPPPPPP\nRNBQKBNR".replace("x","........\n");}

```

10 bytes saved compared to hardcoded output thanks to *@SLC*'s approach in his C# answer.

Try it here.

**Output:**

```
rnbqkbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKBNR

```

# Answer
> 2 votes
# C, 97 bytes

```
char *e="........\n";main(){printf("rnbqkbnr\npppppppp\n%s%s%s%sPPPPPPPP\nRNBQKBNR\n",e,e,e,e);}

```

# Answer
> 2 votes
# Python 3, 64 bytes

Based off DLosc answer to Python 2 as on mine I could not improve.

```
print(*["rnbqkbnr","p"*8]+["."*8]*4+["P"*8,"RNBQKBNR"],sep="\n")

```

1 byte less compared to using "\n".join

```
print("\n".join(["rnbqkbnr","p"*8]+["."*8]*4+["P"*8,"RNBQKBNR"]))

```

# Answer
> 2 votes
# q, 51 bytes

```
"\n"sv flip{x,"p...P","c"$("i"$x)-32}each"rnbqkbnr"

```

# Answer
> 2 votes
# C#, ~~85~~ ~~84~~ ~~83~~ 74 bytes

Edit: Accidentally had too many rows of blank spaces!

Edit: Freed an extra character and fixed the ordering (accidentally had it all reversed) many thanks to @KevinCruijssen

Edit: Reverted back to 83 cos I had the prawns on the wrong line

Edit: Thanks to @adrianmp who helped me shrink it further by omitting return

Using the same format as @adrianmp answer above:

```
x=>"rnbqkbnr\npppppppp\nxxxxRNBQKBNR\nPPPPPPPP".Replace("x","........\n");

```

Full program using the above function:

```
using System;

namespace DrawAnASCIIChessBoard
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<object, string> f =
                x=>"rnbqkbnr\npppppppp\nxxxxRNBQKBNR\nPPPPPPPP".Replace("x","........\n");
                    Console.WriteLine(f(1));
        }
    }
}

```

# Answer
> 2 votes
# Vim, 35 bytes

```
4irnbqkbnr<cr><esc>ddVkr.kVrpkyG:g//m0<cr>gUGP

```

```
4irnbqkbnr<cr><esc> # enter 4 lines, each containing the lowercase figures
dd                  # delete the empty line at the bottom
Vkr.                # replace the bottom two lines with '.'s
kVrp                # replace the next line up with 'p's
kyG                 # go up and copy all lines
:g//m0<cr>          # move the lines with periods to the top
                    # now instead of the black half of the board, we have the white half
gUG                 # change all characters upper case
P                   # paste what we had copied before (the black half) above the current line

```

The `:g//m0` trick is copied from this answer by Lynn.

# Answer
> 2 votes
# C, 113 92 bytes

```
main(){printf("rnbqkbnr\npppppppp\n%s%1$s%1$s%1$s%1$s%1$sPPPPPPPP\nRNBQKBNR","........\n");}

```

This makes use of the `%1$s` parameter-position to repeat the empty lines. Sorry, Matthew Greci, I don't have any reputation here to comment on your solution (you could also have removed some whutespace to get yours down a bit.

Edit 1: Removed arguments (thanks Martin Ender), removed a few too many empty-square lines.

# Answer
> 2 votes
# Python 3, 60 bytes

```
print('rnbqkbnr','p'*8,*['.'*8]*4,'P'*8,'RNBQKBNR',sep='\n')

```

# Answer
> 2 votes
# Python, 69 bytes

```
n='\n'
p,a='p'*8+n,'rnbqkbnr'+n
print a+p+('.'*8+n)*4+(p+a).upper()

```

There are two things that frustrate me with this code: the print and "upper". Wouldn't an `up` function be cool? Anyway, here's my first golf answer.

# Answer
> 2 votes
# Common Lisp, ~~72~~ ~~69~~ ~~68~~ ~~65~~ ~~63~~ 59 bytes

```
(format t"rnbqkbnr
~8@{p~}
~4@{~8@{.~}
~}~8{P~}
RNBQKBNR"1)

```

Ideas for improvement are welcomed.

# Answer
> 2 votes
# Perl, 58 Bytes

```
say for map/../?$_:$_ x8,qw(rnbqkbnr p . . . . P RNBQKBNR)

```

Run like this:

```
perl -E'say for map/../?$_:$_ x8,qw(rnbqkbnr p . . . . P RNBQKBNR)'

```

For each elem in the list (qw), print (say) the element if its length is two (or more) or print the element eight times if just length of one.

# Answer
> 2 votes
# Japt, 23 bytes

```
`rnbqkbnr`y+"p.."
y_+Ôu

```

Test it

```
`rnbqkbnr`           //String "rnbqkbnr"
          y          //Map each column
           +"p.."    //  and add "p.." to the column
                     //Save to variable 'U'
y_                   //Map each column again
   Ôu                //Reversed, then converted to uppercase
  +                  //Append that

```

# Answer
> 2 votes
# C (gcc), 81 bytes

```
f(){printf("rnbqkbnr\npppppppp\n%s%1$s%1$s%1$sPPPPPPPP\nRNBQKBNR","........\n");}

```

I'd try reusing more but that wouldn't beat the naive solution because there's no easy `upper()` or `lower()` functions.

Try it online!

# C (gcc), 92 bytes

```
f(){puts("rnbqkbnr\npppppppp\n........\n........\n........\n........\nPPPPPPPP\nRNBQKBNR");}

```

When not overthinking it, this is the best solution.

Try it online!

# Answer
> 2 votes
## Python 3.8, 64 bytes

I've just started code-golfing, so I'm not very good at it. This is what I got.

```
print('rnbqkbnr\n'+'p'*8+('\n'+'.'*8)*4+'\n'+'P'*8+'\nRNBQKBNR')

```

Try it online

# Answer
> 2 votes
# StupidStackLanguage, 159 bytes

```
avvqimqvdflfqwwddflqiiifqwdfbblfbflfavvflddfffffffflfqvvvvvvvifffffffflflfffffffflflfffffffflflfffffffflflvvvvvvvdfffffffflfliifqwifqwwddfbldfldddfwwifvviifbif

```

Try it online!

Note: Due to StupidStackLanguage not being on tio.run, I have linked the python interpreter with the program loaded in. Close the header and footer tabs to hide the interpreter and only show the StupidStackLanguage program & output.

# Answer
> 2 votes
# Python, ~~70~~ 60 bytes

```
print("rnbqkbnr","p"*8,*["."*8]*4,"P"*8,"RNBQKBNR",sep='\n')

```

Also if someone could explain to me why this doesn't work, I'd appreciate it!

```
map(print,["rnbqkbnr","p"*8,*["."*8]*4,"P"*8,"RNBQKBNR"])

```

# Answer
> 2 votes
# K (ngn/k), ~~28~~ 26 bytes

-2 bytes from @ngn's improvements

```
|a,_|a:+"RNBQKBNR",\:"P.."

```

Try it online!

* `"RNBQKBNR",\:"P.."` prepend each of `"RNBQKBNR"` to `"P.."`
* `a:+` tranpose this, storing in variable `a`. this generates the capitalized half of the chess board.
* `|a,_|` append the lower-cased, reversed lines to the upper-cased lines. reverse again to put the lower-cased lines at the top and the upper-cased lines at the bottom

# Answer
> 2 votes
# POSIX Shell + Utilities, 58 bytes

```
printf rnbqkbnr%08d%32sPPPPPPPPRNBQKBNR|tr 0\  p.|fold -w8

```

Always nice to outdo a Bash-specific solution :)

```
$ cat cg; echo; wc -c cg
printf rnbqkbnr%08d%32sPPPPPPPPRNBQKBNR|tr 0\  p.|fold -w8
58 cg
$ ./cg
rnbqkbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKBNR

```

# Answer
> 1 votes
# Jolf, 32 bytes

```
pη++γͺ"rnbqkbnr"*8'p*²*8'.6ΜγdBH

```

I oughta remake this language soon... Try it here!

Bonus: all-ascii version:

```
pη++on~."rnbqkbnr"*8'p*~:*8'.6ΜndBH

```

## Explanation

```
pη++γͺ"rnbqkbnr"*8'p*²*8'.6ΜγdBH
     ͺ                           pair
      "rnbqkbnr"                  this string
                *8'p              and 8 p's
    γ                            (call this γ)
   +                             add that with
                      *8'.        8 .'s
                     ²             wrapped in an array
                    *     6         repeated 6 times
  +                               add THAT with
                            Μγd    γ mapped over
                              BH   the uppercase version of H
pη                                and join all this with newlines

```

# Answer
> 1 votes
## Vim, 50 strokes

```
qairnbqkbnr<enter><esc>8ip<esc><enter><esc>q3@a3ggqaVr.gqj@aj@aj@ajgU$jgU$

```

Golfed out 8 bits thanks to @DJMcMayhem

# Answer
> 1 votes
## Racket 82 bytes

```
(display"rnbqknbr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKNBR")

```

Another version: 162 bytes

```
(display(string-append"rnbqknbr\n"(make-string 8 #\p)(list->string(for/list((i
(range 0 37)))(if(= 0(modulo i 9))#\newline #\.)))(make-string 8 #\P)"\nRNBQKNBR"))

```

Ungolfed:

```
(define (f)
  (display (string-append
            "rnbqknbr\n"
            (make-string 8 #\p)
            (list->string
             (for/list ((i (range 0 37)))
               (if(= 0 (modulo i 9)) #\newline #\.)))
            (make-string 8 #\P)
            "\nRNBQKNBR"))
  )

```

Testing:

```
(f)

```

Output:

```
rnbqknbr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKNBR

```

# Answer
> 1 votes
# Japt, 37 bytes

```
[A="rnbqkbnr"B='pp8 C='.p8 CCCBu Au]·

```

I really oughta remake this language soon... Test it online!

### How it works

```
[                                  ]  // Wrap all of the following in an array:
 A="rnbqkbnr"                         //   A = "rnbqkbnr",
             B='pp8                   //   B = 8 "p"s,
                    C='.p8            //   C = 8 periods,
                           CCC        //   3 more copies of C,
                              Bu      //   B.toUpperCase(),
                                 Au   //   and A.toUpperCase().
                                    · // Join everything with newlines and implicitly print.

```

# Answer
> 1 votes
# Bash, 73 bytes

```
e=........\\n
echo -e "rnbqkbnr\npppppppp\n$e$e$e${e}PPPPPPPP\nRNBQKBNR"

```

# Answer
> 1 votes
## Python 2, 61 bytes

```
print'rnbqkbnr\npppppppp\n'+('.'*8+'\n')*4+'P'*8+'\nRNBQKBNR'

```

Very brute-force. The `'P'*8` is worth it on the right, but the left `pppppppp` is flanked by newlines that make it not worth doing as `'p'*8`.

# Answer
> 1 votes
# JavaScript (ES6), ~~63~~ 75 bytes

original

```
a=`rnbqkbnr
`;for(j of'p....P')a+=j.repeat(8)+`
`;a+='RNBQKBNR'

```

edited, with output integrated:

```
a=`rnbqkbnr
`;for(j of'p....P')a+=j.repeat(8)+`
`;console.log(a+'RNBQKBNR')

```

alternative version using throw but I think this is not valid because write extra output. Total 69 bytes:

```
a=`
rnbqkbnr
`;for(j of'p....P')a+=j.repeat(8)+`
`;throw a+'RNBQKBNR'

```

# Answer
> 1 votes
# CJam, ~~29~~ 28 bytes

```
"rnbqkbnr"{"p.."+_W%eu+}%zN*

```

Try it online!

---

**Explanation:**

This new version saves a byte by doing the work on columns inside a map `{ }%` instead of `8*`-ing rows. An interesting feature is that the string (array of chars) becomes an array of strings which can then be transposed without splitting.

```
"rnbqkbnr"  e# hard-coded pieces
{           e# do to each piece
  "p.."+    e# append "p.."
  _W%       e# copy and reverse
  eu+       e# capitalize and append
}%z         e# transpose to rows
N*          e# insert newlines

```

# Answer
> 1 votes
# Xasm, 944 Bytes

```
00000001 114
00000001 110
00000001 98
00000001 113
00000001 107
00000001 98
00000001 110
00000001 114
00000001 10
00000001 112
00000001 112
00000001 112
00000001 112
00000001 112
00000001 112
00000001 112
00000001 112
00000001 10
00000001 46
00000001 46
00000001 46
00000001 46
00000001 46
00000001 46
00000001 46
00000001 46
00000001 10
00000001 46
00000001 46
00000001 46
00000001 46
00000001 46
00000001 46
00000001 46
00000001 46
00000001 10
00000001 46
00000001 46
00000001 46
00000001 46
00000001 46
00000001 46
00000001 46
00000001 46
00000001 10
00000001 46
00000001 46
00000001 46
00000001 46
00000001 46
00000001 46
00000001 46
00000001 46
00000001 10
00000001 80
00000001 80
00000001 80
00000001 80
00000001 80
00000001 80
00000001 80
00000001 80
00000001 10
00000001 82
00000001 78
00000001 66
00000001 81
00000001 75
00000001 66
00000001 78
00000001 82
00000011

```

I just did this for novelty. I won't win shortest code but maybe longest! `^_^`

# Answer
> 1 votes
# Charcoal, 32 bytes

```
rnbkqbnr¶Ｐ×p⁸Ｍ⁵↓⁺×P⁸¶RNBKQBNRＵＢ.

```

### Explanation

```
rnbkqbnr¶                            Print "rnbkqbnr\n"
         Ｐ×p⁸                       Print "p" * 8 without moving cursor
              Ｍ⁵↓                   Move cursor 5 characters down
                  ⁺×P⁸¶RNBKQBNR      Print "p" * 8 + "\nRNBKQBNR"
                               ＵＢ. Set background to '.'

```

# Answer
> 1 votes
# SX, 65 bytes

```
我("""rnbqkbnr
pppppppp
"""+('.'*8+"\n")*4+"PPPPPPPP\nRNBQKBNR")

```

By the way, I am planning on making some radical changes to SX to make it better for code golfing.

# Answer
> 1 votes
**Jvascript 152 Bytes \- 146 Bytes \- 99 Bytes**

Golfed code:

```
(n="rnbqkbnr",l=`
`,s=l+"........",t=n+l+"pppppppp"+s+s)=>t+l+[...t].reverse().join``.toUpperCase()

```

Ungolfed:

```
t = (n = "rnbqkbnr", l = "\n", s = l + ".".repeat(8), t = n + l + "p".repeat(8) + s + s) => {
        console.log(t + l + t.split("").reverse().join("").toUpperCase());
    }
    (() => { t(); })();

```

# Answer
> 1 votes
# Pyth, ~~41 35 34~~ 33 Bytes

```
K*z\p8J"rnbqkbnr"JKp*+*\.8b4rK1rJ1

```

Golfed a byte thanks to **@daHugLenny**

Try It Online

**Explanation**

```
K*\p8          K="pppppppp"
J"rnbqkbnr"    J="rnbqkbnr"
J              print The Variable J
K              print The Variable K
p+*+*\.8b4     print"........\n" 4 times
rK1            print K but in uppercase
rJ1            print J but in uppercase

```

# Answer
> 1 votes
# Scala, 65 bytes

```
Seq("rnbqkbnr","p",".",".",".",".","P","RNBQKBNR")map(_*8 take 8)

```

Really straightforward; makes use of the repeat 8 times and take the first 8 chars

# Answer
> 1 votes
# Python 3, 83 Bytes

```
t="rnbqkbnr"
n="\n"
print((t)+n+("p"*8)+n+(("."*8+"\n")*4)+n+("P"*8)+n+(t.upper()))

```

# Answer
> 1 votes
# SmileBASIC, 52 bytes

```
?"rnbqkbnr
?"p"*8?("."*8+CHR$(10))*4;"P"*8?"RNBQKBNR

```

# Answer
> 1 votes
# 8th, 74 bytes

**Code**

```
"RNBQKBNR\n" dup lc . "PPPPPPPP\n" dup lc . ( "........\n" . ) 4 times . .

```

**Output**

```
ok> "RNBQKBNR\n" dup lc . "PPPPPPPP\n" dup lc . ( "........\n" . ) 4 times . .
rnbqkbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKBNR

```

# Answer
> 1 votes
# T-SQL, 70 bytes

```
PRINT REPLACE('rnbqkbnr
pppppppp
1111PPPPPPPP
RNBQKBNR',1,'........
')

```

SQL allows line breaks inside quotes, I used that in both the main and the replaced strings. Using a numeral instead of a symbol as my replacement character lets me save 2 additional bytes.

Tried to replace the other two strings, but couldn't find anything shorter than **80 bytes**:

```
SELECT r+p+e+e+e+e+UPPER(p+r)FROM(SELECT'rnbqkbnr
'r,'pppppppp
'p,'........
'e)a

```

# Answer
> 1 votes
# Japt `-R`, 28 bytes

```
`rnbqkbnr p . .`¸m!î8
cUmu w

```

Test it

# Answer
> 1 votes
# Zsh, ~~69~~ 65 bytes

~~69bytes~~ try it online!!

build array, print it forwards, print it backwards+lowercase

```
D=........ X=(RNBQKBNR PPPPPPPP $D $D);printf %s\\n $X ${(Oa)X:l}

```

# Answer
> 1 votes
# Keg, ~~43+1~~ ~~40~~ ~~39~~ 37 bytes

```
rnbqkbnr
∑p)
(4|`.`8*
)(8|P)
RNBQKBNR

```

Try it online!

## Answer History

### 39 bytes

```
rnbqkbnr
(8|p)
(4|`.`8*
)(8|P)
RNBQKBNR

```

Try it online!

### 40 bytes

```
rnbqkbnr
(8|p)
(4|(8|\.)
)(8|P)
RNBQKBNR

```

Try it online!

*-4 bytes due to fixing a bug. That's new.*

## 44 bytes

```
rnbqkbnr\
(8|p)\
(4|(8|\.)\
)(8|P)\
RNBQKBNR

```

Try it online!

Run length encoding where possible. Implicitly print the result.

## In depth:

```
rnbqkbnr    #push rnbqkbnr
(8|p)   #8 times, push the letter "p"
\   #escaped newline
(4| #4 times, do
    (8|\.   #8 times, push "."
)\  #then push a newline
)
(8|P)   #8 times, push P
\       #escaped newline
RNBQKBNR    #push RNBQKBNR

```

# Answer
> 1 votes
# Wren, 61 bytes

I suppose this is not a good way of programming, but this is worth it when it comes to code golf.

```
Fn.new{"rnbqkbnr
"+"p"*8+"
"+("."*8+"
")*4+"P"*8+"
RNBQKBNR"}

```

Try it online!

## Explanation

```
Fn.new{          // New function
       "rnbqkbnr
"                // rnbqkbnr\n
+"p"*8           // pppppppp
+"
"                // \n
+("."*8          // ........
       +"
"                // \n
)*4              // above strings 4 times
   +"P"*8        // PPPPPPPP
         +"
RNBQKBNR"        // \nRNBQKBNR
}

```

# Answer
> 1 votes
# Python 3, ~~66~~ 64 bytes

# 64 bytes:

```
print('rnbqkbnr','p'*8,('.'*8+'\n')*4,'P'*8,'RNBQKBNR',sep='\n')

```

### Logic:

1. Pieces remain the same as previously
2. pawns and dots get repeated 8 times
3. "." is appended a new line and the whole thing is repeated 4 times.
4. entire print is separated with sep='\n'

---

# 66 bytes:

```
print('\n'.join(['rnbqkbnr']+[i*8for i in 'p....P']+['RNBQKBNR']))

```

### Logic:

1. create the piece arrays as is at first and last positions.
2. create the middle 6 rows by list comprehension - using repetition `i*8`.
3. Sum the lists to get 8 elements
4. Join elements with a line break in between (`\n`)
5. `print()`

### Output:

```
rnbqkbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKBNR

```

# Answer
> 1 votes
# JavaScript (Babel Node), ~~89~~ 81 bytes

```
console.log("rnbqkbnr\npppppppp\n"+"........\n".repeat(4)+"PPPPPPPP\nRNBQKBNR\n")

```

Try it online!

# Answer
> 1 votes
# Stax, ~~22~~ 21 bytes

```
î}-øΓ╤Ö¼└°≤╠ç]♀WσG`pÑ

```

Run and debug it

# Answer
> 1 votes
# Pyth, 27 bytes

```
js.erbk_B+"rnbqkbnr"*L8"p..

```

Try it online!

```
js.erbk_B+"rnbqkbnr"*L8"p..
                       "p..   The string "p.."
                    *L8       Repeat each character 8 times, yields ["pppppppp", "........", "........"]
         +"rnbqkbnr"          Prepend "rnbqkbnr" to the list
       _B                     Pair the list with itself, reversed
  .e                          Map as b, with index k:
    rbk                         Change case of elements of b
                                The r token converts to lower case if one of the arguments is 0, and
                                converts to uppercase if one of the arguments is 1.
 s                            Concatenate the two halves of the output
j                             Join on newlines, implicit print

```

# Answer
> 1 votes
# JavaScript (V8), 65 bytes

```
_=>`rnbqkbnr
pppppppp
`+`........
`.repeat(4)+`PPPPPPPP
RNBQKBNR`

```

Try it online!

# Explanation :

```
_ =>            // beginning of function param is not needed so we do _ instead of ()
    `rnbqkbnr
pppppppp
`             // first two lines are written better than doing line1+\n+line2+\n
+             // add to it
`........
`repeat(4)   // repeat this line of ........ 4 times
+`PPPPPPPP
RNBQKBNR`    // last two lines

```

# Answer
> 1 votes
# APL(Dyalog Unicode), <sup>~~26~~</sup> 25 bytes <sup>SBCS</sup>

Taking some inspiration from coltim's K answer.

-1 byte thanks to Razetime!

```
(⎕C⍪⊖)'RNBQKBNR'⍪8/⍪'P..'

```

Try it on APLgolf! or Get some intermediate values

---

# APL(Dyalog Unicode), <sup>~~30~~</sup> 28 bytes <sup>SBCS</sup>

```
(⎕C∘⊖⍪⊢)⍉'..P'⍪⍤1⍪'RNBQKBNR'

```

Try it on APLgolf!

`⍪'RNBQKBNR'` Make a 8x1 matrix of characters
`'..P'⍪⍤1` Prepend three columns made from the characters from `'..P'`
Transpose to get the bottom half of the result
`⎕C∘⊖` Mirror vertically and convert to lower case
`⍪⊢` Stack this on top of the bottom half

Try it with step by step output

# Answer
> 1 votes
# Thunno `N`, \\$28 \log\_{256}(96) \approx\\$ 23 bytes

(The leaderboard needs an integer, so I rounded it. It's actually 23.05 bytes)

```
"rnbqkbnr"'p8*'.8*DZMDrusA+r

```

Attempt This Online!

Port of Emigna's 05AB1E answer.

```
"rnbqkbnr"  # Push "rnbqkbnr"           STACK: "rnbqkbnr"
'p8*        # Push "pppppppp"           STACK: "rnbqkbnr", "pppppppp"
'.8*D       # Push "........" twice     STACK: "rnbqkbnr", "pppppppp", "........", "........"
ZMD         # Push the stack twice      STACK: ["rnbqkbnr", "pppppppp", "........", "........"],
                                               ["rnbqkbnr", "pppppppp", "........", "........"]
ru          # Reverse, uppercase        STACK: ["rnbqkbnr", "pppppppp", "........", "........"],
                                               ["........", "........", "PPPPPPPP", "RNBQKBNR"]
sA+         # Concatenate               STACK: ['RNBQKBNR', 'PPPPPPPP', '........', '........',
                                                '........', '........', 'pppppppp', 'rnbqkbnr']
r           # Reverse                   STACK: ['rnbqkbnr', 'pppppppp', '........', '........',
                                                '........', '........', 'PPPPPPPP', 'RNBQKBNR']
            # N flag joins by newlines

```

# Answer
> 1 votes
# Python 3, 80 bytes

```
print(*(l:=["rnbqkbnr",'p'*8,b:='.'*8,b]),*[m.upper()for m in l][::-1],sep='\n')

```

Try it online!

When you first look at this code, you might ask: why so many asterisks? 2 asterisks are splat operators, and the other 2 are string multiplication.

I'll first work from the inner-most layer of code and I'll work the way up, explaining everything.

We make a variable `b`, which is one of the blank lines. Which is the string `'.'` repeated 8 times. We put that and another copy of `b`.

That is inside a list, which has some more items before that. There's the top row and the pawn row (`'p'` repeated 8 times). That is saved into a variable `l` and splatted into `print`.

Then we have a comprehension, which makes every line in `l` have uppercase letters (white's side). We need to reverse that array and then splat it into `print`.

Finally, we use the new line as an argument separator and we are done!

# Answer
> 1 votes
# Vis editor, 36 bytes

```
irnbqkbnr<Escape>5o<Escape>4<Ctrl-k>:i8/.<Enter><Escape>08rpykGpddpVkU
irnbqkbnrX5oX4K:i8/.NX08rpykGpddpVkU

```

Sequences and are counted as 1 byte each.

1. `i` \- Insert the first row.
2. `<E>5o<E>` \- Add 5 newlines under the first line, cursor is now at end of file.
3. `4<C-k>` \- Add 4 additional cursors above current cursor
4. `:i8/.` \- Use a Sam command to insert 8 periods at all 5 cursor locations. Still in NORMAL mode.
5. `<Esc>` \- Get rid of all but the primary cursor, which is conveniently located at the 2nd line. Still in NORMAL mode.
6. `08rp` \- Go to begining and replace the following 8 dots with `p`.
7. `yk` \- Yank current line and line above (j is down, k is up).
8. `G` \- Jump to end of file.
9. `pddp` \- Paste 1st and 2nd line, then swap them.
10. `VkU` \- Select entire last line and line above (as before, k is up), uppercase both.

I had a slightly shorter codegolf in vis, but this is more instructure because it uses a Sam expression `:i8/` and multi cursors (including the location of the primary cursor).

```
rnbqkbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKBNR

```

# Answer
> 1 votes
# Python 3, 75 bytes

```
lambda a="rnbqkbnr",b="p"*8:"\n".join([a,b,*["."*8]*4,b.upper(),a.upper()])

```

Try it online!

# Answer
> 0 votes
# Mathematica, ~~76~~ 72 bytes

```
{"rnbqkbnr
","p"~(t=Table)~8,"
",t["."~t~8<>"
",4],"P"~t~8}<>"
RNBQKBNR"

```

`Table` is used to generate lists of strings. When lists of strings meet the concatenation operator `<>`, they get flattened into strings automatically, so the construction `{` ... `,` ... `,` ... `}<>`... is preferred over using `<>` throughout when there are sufficiently many strings to be concatenated.

Also 72 bytes:

```
{"rnbqkbnr
","p"~(t=Table)~8,"
",{"."~t~8,"
"}~t~4,"P"~t~8}<>"
RNBQKBNR"

```

In comparison, the direct string itself is 73 bytes:

```
"rnbqkbnr
pppppppp
........
........
........
........
PPPPPPPP
RNBQKBNR"

```

# Answer
> 0 votes
# Dart, 62 bytes

```
f()=>"rnbqkbnr\n${"p"*8}\n${"........\n"*4+"P"*8}\nRNBQKBNR";

```

I am annoyed that I can't reduce the `"........\n"*4` part further, but due to the newline being included in the multiplication, all rewrites come out at the same length as the original:

```
"${"."*8}\n"*4
("."*8+"\n")*4
"........\n"*4

```

Dart's string functions, like `toUpperCase()`, have too long names to use them in golfing.

# Answer
> 0 votes
# PHP, ~~67~~ ~~64~~ ~~63~~ 62 bytes

Note: uses IBM-850 encoding.

```
<?=~str_pad(ìæØÄöØæì§ÅÅÅÅÅÅÅÅ,54,§ÐÐÐÐÐÐÐÐ)?>PPPPPPPP
RNBQKBNR

```

Run like this:

```
echo '<?=~str_pad(ìæØÄöØæì§ÅÅÅÅÅÅÅÅ,54,§ÐÐÐÐÐÐÐÐ)?>PPPPPPPP
RNBQKBNR' | php 2>/dev/null;echo

```

And in "unencoded" form:

```
echo '<?=str_pad("rnbqkbnr\npppppppp",54,"\n........"),"PPPPPPPP\nRNBQKBNR";' | php 2>/dev/null;echo

```

# Explanation

Unfortunately I couldn't find a more interesting approach (that actually saves bytes) than to just print the string, except for the 4 middle lines which are repeated using ~~`str_repeat`~~ `str_pad`.

# Tweaks

* Saved 3 bytes by replacing `str_repeat` with `str_pad`.
* Saved a byte by using closing tag, thx to user59178.
* Saved a byte by changing the pad string to start with a newline, so last newline can be dropped from the first argument of `str_pad`

# Answer
> 0 votes
# Perl 5, 49 bytes

```
print join$/,$_=rnbqkbnr,"p"x8,("."x8)x4,"P"x8,uc

```

If only we had something like `p` instead of `print`, the remaining legible words could be removed.

```
print join $/, ...    - print the items joined by the input
                        record separator, $/, which is "\n" by default
$_ = rnbqkbnr         - set (and return) the default variable.
                        A bare string is taken as a string constant,
                        but gives a warning...  but only if they're enabled
"p" x 8               - string multiplier
("."x8)x4             - string and list multiplier.
"P" x 8               - same
uc                    - uppercase, if no expression given, uses $_

```

Of course this depends on the order of evaluation of the parameters to `join`, as `$_` needs to be set before `uc` is called. Also, this doesn't print a trailing newline, which makes it look ugly if executed from the command line.

# Answer
> 0 votes
# SQL, 146 Bytes

```
declare @ char(8)='rnbqkbnr'
print 'pppppppp'
print '........'
print '........'
print '........'
print '........'
print 'PPPPPPPP'
print upper(@)

```

# Answer
> 0 votes
# Microscript II, 56 bytes

```
"rnbqkbnr\npppppppp"P"........"PPPP"PPPPPPPP\nRNBQKBNR"

```

# Answer
> 0 votes
# tcl, 86

```
proc R {s n\ 8} {string repe $s $n}
puts rnbqkbnr\n[R p]\n[R [R .]\n 4][R P]\nRNBQKBNR

```

demo

# Answer
> 0 votes
# Japt `-R`, 25 bytes

```
"rnbqkbnr"¬m+'.²ip)®+ÔuÃÕ

```

Test it

```
"rnbqkbnr"¬m+'.²ip)®+ÔuÃÕ
"rnbqkbnr"                    :String literal
          ¬                   :Split
           m+                 :Map & append
             '.²              :  "." repeated twice
                ip            :  Prepend "p"
                  )           :End map
                   ®+         :Map & append
                     Ô        :  Reversed string
                      u       :  Uppercased
                       Ã      :End map
                        Õ     :Transpose
                              :Implicit output, joined by newlines

```

# Answer
> 0 votes
# brainfuck, 248 bytes

There is probably a better way to do this.

```
++++++++++[>+>+++++++++++>++++++++>++++++++++>+++++<<<<<-]>>++++>>-->----<<<.----.>>.<<+++.------.>>.<<+++.++++.<.>--........<.>>>>>++++++[<........<<<<.>>>>>-]<<<........<<.>>++.----.------------.+++++++++++++++.------.---------.++++++++++++.++++.

```

Try it online!

# Answer
> 0 votes
# C, 86 bytes

```
k(x,y){for(y=x=8;y;putchar(!x--?--y,x=8,10:"RNBKQBNR.P"[y-3u<4?8:y%5^2?x:9]+y/7*32));}

```

Yet another attempt to golf a loop.

# Answer
> 0 votes
# Swift, 113 bytes

```
func p()->String{var m="rnbqkbnr";for c in "p....P"{m+="\n";for _ in 1...8{m+="\(c)"}};m+="\nRNBQKBNR";return m}

```

(Start with the first row, append 8 times p, . and P and then append the last row.)

# Answer
> 0 votes
# Swift, 80 bytes

```
var c="rnbqkbnr\npppppppp\n\({String.init}()("........\n",4))PPPPPPPP\nRNBQKBNR"

```

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---


# Question
Title: Sort the unique numbers in a multiplication table
Pretty simple challenge today:

Write a program or function that takes in a positive integer N and prints or returns a ***sorted*** list of the ***unique*** numbers that appear in the multiplication table whose row and column multiplicands both range from 1 to N inclusive.

The list may be sorted in ascending order (smallest to largest) or descending order (largest to smallest), and may be output in any reasonable format.

**The shortest code in bytes wins!**

# Example

When N = 4, the multiplication table looks like:

```
   1  2  3  4
  -----------
1| 1  2  3  4
 |
2| 2  4  6  8
 |
3| 3  6  9 12
 |
4| 4  8 12 16

```

The unique numbers in the table are `1, 2, 3, 4, 6, 8, 9, 12, 16`. These are already sorted, so

```
1, 2, 3, 4, 6, 8, 9, 12, 16

```

might be your exact output for N = 4. But since the sorting can be reversed and there's some leeway in the formatting, these would also be valid outputs:

```
[16,12,9,8,6,4,3,2,1]
```

```
1
2
3
4
6
8
9
12
16
```

```
16 12 9 8 4 3 2 1
```

# Test Cases

```
N=1 -> [1]
N=2 -> [1, 2, 4]
N=3 -> [1, 2, 3, 4, 6, 9]
N=4 -> [1, 2, 3, 4, 6, 8, 9, 12, 16]
N=5 -> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 20, 25]
N=6 -> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 30, 36]
N=7 -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 28, 30, 35, 36, 42, 49]
N=8 -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 28, 30, 32, 35, 36, 40, 42, 48, 49, 56, 64]
N=9 -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27, 28, 30, 32, 35, 36, 40, 42, 45, 48, 49, 54, 56, 63, 64, 72, 81]
N=10 -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27, 28, 30, 32, 35, 36, 40, 42, 45, 48, 49, 50, 54, 56, 60, 63, 64, 70, 72, 80, 81, 90, 100]
N=11 -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 27, 28, 30, 32, 33, 35, 36, 40, 42, 44, 45, 48, 49, 50, 54, 55, 56, 60, 63, 64, 66, 70, 72, 77, 80, 81, 88, 90, 99, 100, 110, 121]
N=12 -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 27, 28, 30, 32, 33, 35, 36, 40, 42, 44, 45, 48, 49, 50, 54, 55, 56, 60, 63, 64, 66, 70, 72, 77, 80, 81, 84, 88, 90, 96, 99, 100, 108, 110, 120, 121, 132, 144]

```

# Answer
# Pyth, 8 bytes

```
S{*M^SQ2

```

Try it online.

Explanation: `SQ` takes the evaluated list input (`Q`) and makes a list `[1, 2, ..., Q]`. `^SQ2` takes the Cartesian product of that list with itself - all possible product combinations. `*M` multiplies all these pairs together to form all possible results in the multiplication table and `S{` makes it unique and sorts it.
> 13 votes

# Answer
# Python 2, ~~61~~ 51 bytes

```
lambda n:sorted({~(i%n)*~(i/n)for i in range(n*n)})

```

Thanks to xnor for shortening some syntax.
> 13 votes

# Answer
# APL, ~~18~~ 16 bytes

```
{y[⍋y←∪,∘.×⍨⍳⍵]}

```

This is an unnamed monadic function. The output is in ascending order.

Explanation:

```
             ⍳⍵]}   ⍝ Get the integers from 1 to the input
         ∘.×⍨       ⍝ Compute the outer product of this with itself
        ,           ⍝ Flatten into an array
       ∪            ⍝ Select unique elements
     y←             ⍝ Assign to y
 {y[⍋               ⍝ Sort ascending

```

Fixed an issue and saved 2 bytes thanks to Thomas Kwa!
> 12 votes

# Answer
# Octave, 22 bytes

```
@(n)unique((a=1:n)'*a)

```
> 7 votes

# Answer
# Julia, 24 bytes

```
n->sort(∪((x=1:n)*x'))

```

This is an anonymous function that accepts an integer and returns an integer array.

Ungolfed:

```
function f(n::Integer)
    # Construct a UnitRange from 1 to the input
    x = 1:n

    # Compute the outer product of x with itself
    o = x * transpose(x)

    # Get the unique elements, implicitly flattening
    # columnwise into an array
    u = unique(o)

    # Return the sorted output
    return sort(u)
end

```
> 7 votes

# Answer
# CJam, ~~14~~ 12 bytes

Latest version with improvements proposed by @aditsu:

```
{)2m*::*0^$}

```

This is an anonymous function. Try it online, with input/output code needed for testing it.

@Martin proposed another very elegant solution (`{,:)_ff*:|$}`) with the same length. I used the one by aditsu because it was much more similar to my original solution.

The main difference to my original solution is that this keeps the `0` value in the original sequence, which saves 2 bytes at the start. You'd think that this would not help, because you have to remove the `0` value from the result. But the core of @aditsu's idea is the `0^` at the end, which is a set difference with `0`. This removes the `0`, and at the same time, since it's a set operation, eliminates duplicate elements from the solution set. Since I already needed 2 bytes to eliminate the duplicates before, removing the `0` is then essentially free.

Explanation:

```
{     Start anonymous function.
  )     Increment to get N+1.
  2m*   Cartesian power, to get all pairs of numbers in range [0, N].
  ::*   Reduce all pairs with multiplication.
  0^    Remove 0, and remove duplicates at the same time since this is a set operation.
  $     Sort the list.
}     End anonymous function.

```
> 7 votes

# Answer
# R, 39 bytes

```
cat(unique(sort(outer(n<-1:scan(),n))))

```

This reads an integer from STDIN and writes a space delimited list to STDOUT.

We create the multiplication table as a matrix using `outer`, implicitly flatten into a vector and sort using `sort`, select unique elements using `unique`, and print space delimited using `cat`.
> 4 votes

# Answer
# MATLAB, 24 bytes

```
@(n)unique((1:n)'*(1:n))

```
> 4 votes

# Answer
# Ruby, ~~50~~ 48 bytes

```
->n{c=*r=1..n;r.map{|i|c|=r.map{|j|i*j}};c.sort}

```

**Ungolfed:**

```
->n {
  c=*r=1..n
  r.map { |i| c|=r.map{|j|i*j} }
  c.sort
}

```

Using nested loop to multiply each number with every other number upto n and then sorting the array.

**50 bytes**

```
->n{r=1..n;r.flat_map{|i|r.map{|j|i*j}}.uniq.sort}

```

**Usage:**

```
->n{c=*r=1..n;r.map{|i|c|=r.map{|j|i*j}};c.sort}[4]
=> [1, 2, 3, 4, 6, 8, 9, 12, 16]

```
> 4 votes

# Answer
## zsh, ~~86~~ 56 bytes

*thanks to @Dennis for saving 30(!) bytes*

```
(for a in {1..$1};for b in {1..$1};echo $[a*b])|sort -nu

```

Explanation / ungolfed:

```
(                      # begin subshell
  for a in {1..$1}     # loop through every pair of multiplicands
    for b in {1..$1}
      echo $[a*b]      # calculate a * b, output to stdout
) | sort -nu           # pipe output of subshell to `sort -nu', sorting
                       # numerically (-n) and removing duplicates (-u for uniq)

```

This doesn't work in Bash because Bash doesn't expand `{1..$1}`—it just interprets it literally (so, `a=5; echo {1..$a}` outputs `{1..5}` instead of `1 2 3 4 5`).
> 4 votes

# Answer
# Shell + common utilities, 41

```
seq -f"seq -f%g*%%g $1" $1|sh|bc|sort -nu

```

---

Or alternatively:

# Bash + coreutils, 48

```
eval printf '%s\\n' \$[{1..$1}*{1..$1}]|sort -nu

```

Constructs a brace expansion inside an arithmetic expansion:

`\$[{1..n}*{1..n}]` expands to the arithmetic expansions `$[1*1] $[1*2] ... $[1*n] ... $[n*n]` which are evaluated and passed to `printf`, which prints one per line, which is piped to `sort`.

Careful use of quotes, escapes and `eval` ensure the expansions happen in the required order.

---

Or alternatively:

# Pure Bash, 60

```
eval a=($(eval echo [\$[{1..$1}*{1..$1}\]]=1))
echo ${!a[@]}

```
> 4 votes

# Answer
# Husk, 6 bytes

```
OumΠπ2

```

Try it online!

### Explanation

```
OumΠπ2
    π2  cartesian square
  mΠ    map product
 u      unique
O       sort

```
> 4 votes

# Answer
## Haskell, ~~55~~ 54 bytes

```
import Data.List
f n=sort$nub[x*y|x<-[1..n],y<-[1..x]]

```

Usage example: `f 4` -\> `[1,2,3,4,6,8,9,12,16]`.

`nub` removes duplicate elements from a list.

Edit: @Zgarb found a superfluous `$`.
> 3 votes

# Answer
# JavaScript (Node.js), 69 bytes

```
n=>[...a=Array(i=n*n)].map(x=>a[q=~(--i%n)*~(i/n)]=q)&&a.filter(x=>x)

```

Try it online!

# JavaScript (Node.js), 76 bytes

```
n=>[...Array(n*n)].flatMap((_,i,x)=>x.every((_,j)=>~(j/n)*~(j%n)+~i)?[]:i+1)

```

Try it online!

No recursion like other answers
> 3 votes

# Answer
# Mathematica, 25 bytes

```
Union@@Array[1##&,{#,#}]&

```
> 2 votes

# Answer
# K, 17 bytes

```
t@<t:?,/t*\:t:1+!

```

Not much to say here. Sort (`t@<t:`) the unique items (`?`) of the flattened (`,/`) multiplied cartesian self-product (`t*\:t:`) of 1 up to and including N (`1+!`).

In action:

```
  t@<t:?,/t*\:t:1+!5
1 2 3 4 5 6 8 9 10 12 15 16 20 25

```
> 2 votes

# Answer
## J, ~~21~~ 20 bytes

*Thanks to @Zgarb for -1 byte!*

```
/:~@~.@,@(1*/~@:+i.)

```

My first J answer! Golfing tips are appreciated, if there is something to golf.

This is a monadic function; we take the outer product by multiplication of the list `1..input` with itself, flatten, take unique elements, and sort.
> 2 votes

# Answer
## Kotlin, 70 bytes

```
val a={i:Int->(1..i).flatMap{(1..i).map{j->it*j}}.distinct().sorted()}

```

Ungolfed version:

```
val a: (Int) -> List<Int> = {
    i -> (1..i).flatMap{ j -> (1..i).map{ k -> j * k } }.distinct().sorted()
}

```

Test it with:

```
fun main(args: Array<String>) {
    for(i in 1..12) {
        println(a(i))
    }
}

```
> 2 votes

# Answer
# Pyt, 7 bytes

```
řĐɐ*ƑỤş

```

Try it online!

```
ř           implicit input (n); push [1,2,...,n]
 Đ          duplicate
  ɐ*        generate multiplication table
    Ƒ       flatten array
     Ụ      get unique elements
      ş     sort in ascending order; implicit print

```
> 2 votes

# Answer
# Thunno, \\$ 12 \log\_{256}(96) \approx \\$ 9.88 bytes

```
R1+DZ!.PZU

```

#### Explanation

```
R1+DZ!.PZUz:  # Implicit input                    Example (n=5)
R1+           # [1..input]                        [1, 2, 3, 4, 5]
   DZ!        # Cartesian product with itself     [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [5, 1], [5, 2], [5, 3], [5, 4], [5, 5]]
      .P      # Product of each inner list        [1, 2, 3, 4, 5, 2, 4, 6, 8, 10, 3, 6, 9, 12, 15, 4, 8, 12, 16, 20, 5, 10, 15, 20, 25]
        ZU    # Uniquified                        [1, 2, 3, 4, 5, 6, 8, 10, 9, 12, 15, 16, 20, 25]
          z:  # And sorted                        [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 20, 25]
              # Implicit output

```

#### Screenshot
> 2 votes

# Answer
# Vyxal, 7 bytes

```
ɾẊƛΠ;Us

```

Try it Online!
> 2 votes

# Answer
# Jelly, 5 bytes

```
Ṭẋ)ST

```

Try it online!

```
  )      For each x in 1 .. n:
Ṭ        Create a list containing 1 at index x and 0s before it,
 ẋ       and repeat it x times.
   S     Sum the results element-wise,
    T    and yield the indices of non-zeros in the result.

```
> 2 votes

# Answer
# Brachylog, 9 bytes

```
⟦₁⟨∋×∋⟩ᵘo

```

Try it online!

### Explanation

```
⟦₁⟨∋×∋⟩ᵘo
⟦₁        Range from 1 to input number, inclusive
      ᵘ   Get all unique outputs of this predicate:
  ∋         Pick a number from that range
    ∋       Pick another number from that range
 ⟨ ×  ⟩      Multiply them together
       o  Sort the resulting list

```
> 2 votes

# Answer
## Minkolang 0.14, ~~25~~ ~~22~~ 18 bytes

I remembered that I very conveniently implemented Cartesian products before this question was posted!

```
1nLI20P[x*1R]sS$N.

```

Try it here. (Outputs in reverse order.)

### Explanation

```
1                     Push a 1 onto the stack
 n                    Take number from input (n)
  L                   Pushes 1,2,...,n onto the stack
   I                  Pushes length of stack so 0P knows how many items to pop
    2                 Pushes 2 (the number of repeats)
     0P               Essentially does itertools.product(range(1,n+1), 2)
       [              Open for loop that repeats n^2 times (0P puts this on the stack)
        x             Dump (I know each product has exactly two numbers
         *            Multiply
          1R          Rotate 1 step to the right
            ]         Close for loop
             s        Sort
              S       Remove duplicates ("set")
               $N.    Output whole stack as numbers and stop.

```
> 1 votes

# Answer
# Pyth, 10

```
S{m*Fd^SQ2

```

Try it Online or run a Test Suite
> 1 votes

# Answer
# C, 96 bytes

```
i,a[1<<16];main(n){for(scanf("%d",&n);i<n*n;a[~(i%n)*~(i++/n)]="%d ");while(i)printf(a[i--],i);}

```

This prints the numbers in descending order. Suggestions are welcomed as this looks far from optimal.
> 1 votes

# Answer
# TeaScript, ~~37~~ 35 chars; 40 bytes

*Saved 2 bytes thanks to @Downgoat*

TeaScript is JavaScript for golfing.

```
(b+r(1,+x¬)ßam(z=>z*l±s`,`.u¡s»l-i)

```

Try it online!

### Ungolfed and explanation

```
(b+r(1,+x+1)m(#am(z=>z*l)))s(',').u()s(#l-i)
              // Implicit: x = input number
r(1,+x+1)     // Generate a range of integers from 1 to x.
m(#           // Map each item "l" in this range "a" to:
 am(z=>       //  a, with each item "z" mapped to
  z*l))       //   z * l.
(b+      )    // Parse this as a string by adding it to an empty string.
s(',')        // Split the string at commas, flattening the list.
.u()          // Take only the unique items from the result.
s(#l-i)       // Sort by subtraction; the default sort sorts 10, 12, 100, etc. before 2.
              // Implicit: output last expression

```
> 1 votes

# Answer
# JavaScript (ES6), ~~92~~ 90 bytes

```
n=>eval(`for(r=[],a=n;a;a--)for(b=n;b;)~r.indexOf(x=a*b--)||r.push(x);r.sort((a,b)=>a-b)`)

```

## Explanation

```
n=>eval(`                 // use eval to remove need for return keyword
  for(r=[],a=n;a;a--)     // iterate for each number a
    for(b=n;b;)           // iterate for each number b
      ~r.indexOf(x=a*b--) // check if it is already in the list, x = value
      ||r.push(x);        // add the result
  r.sort((a,b)=>a-b)      // sort the results by ascending value
                          // implicit: return r
`)

```

## Test

```
N = <input type="number" oninput="result.innerHTML=(

n=>eval(`for(r=[],a=n;a;a--)for(b=n;b;)~r.indexOf(x=a*b--)||r.push(x);r.sort((a,b)=>a-b)`)

)(+this.value)" /><pre id="result"></pre>
```
> 1 votes

# Answer
## Perl 6, 27 bytes

```
{squish sort 1..$_ X*1..$_} # 27
{unique sort 1..$_ X*1..$_} # 27
{sort unique 1..$_ X*1..$_} # 27

```

Example usage:

```
say {squish sort 1..$_ X*1..$_}(3); # (1 2 3 4 6 9)␤

my $code = {squish sort 1..$_ X*1..$_}

for 1..100 -> \N { say $code(N) }

my &code = $code;

say code 4; # (1 2 3 4 6 8 9 12 16)␤

```
> 1 votes

# Answer
## Haskell, 51 bytes

```
f n=[i|i<-[1..n*n],elem i[a*b|a<-[1..n],b<-[1..n]]]

```

Pretty boring. Just filters the list `[1..n*n]` to the elements of the form `a*b` with `a` and `b` in `[1..n]`. Using `filter` gives the same length

```
f n=filter(`elem`[a*b|a<-[1..n],b<-[1..n]])[1..n*n]

```

I tried for a while to generate the list of products with something more clever like `concatMap` or `mapM`, but only got longer results. A more sophisticated check of membership came in at 52 bytes, 1 byte longer, but can perhaps be shortened.

```
f n=[k|k<-[1..n*n],any(\a->k`mod`a<1&&k<=n*a)[1..n]]

```
> 1 votes

# Answer
# JAVA - 86 Bytes

```
Set a(int a){Set s=new TreeSet();for(;a>0;a--)for(int b=a;b>0;)s.add(a*b--);return s;}

```

---

# Ungolfed

```
Set a(int a){
    Set s = new TreeSet();
    for (;a>0;a--){
        for(int b = a;b>0;){
            s.add(a*b--);
        }
    }
    return s;
}

```
> 1 votes

# Answer
## Pyth, 11 bytes

```
S{sm*RdSdSQ

```

This is similar to the Julia answer. Thanks to @Maltysen
> 1 votes

# Answer
# PHP, 74,73 70bytes

```
while($i++<$j=$n)while($j)$a[]=$i*$j--;$a=array_unique($a);sort($a);

print_r($a); // Not counted, but to verify the result

```

Ungolfed:

```
while($i++<$j=$n)
    while($j)
        $a[]=$i*$j--;

```

---

Previous:

`while(($j=$i++)<$n)for(;$j++<$n;)$a[]=$i*$j;$a=array_unique($a);sort($a);`

Not 100% sure what to do with output, but `$a` contains an array with the corresponding numbers. `$n` is the number geven via `$_GET['n']`, with `register_globals=1`
> 1 votes

# Answer
# Python 3, 57 bytes

`r=range(1,n+1);print(sorted({i*j for i in r for j in r}))`
> 1 votes

# Answer
# Japt, ~~13~~ ~~12~~ ~~11~~ ~~13~~ ~~11~~ ~~8~~ 7 bytes

```
õ ï* Íâ

```

Try it

```
õ ï* Íâ     :Implicit input of integer U
õ           :Range [1,U]
  ï         :Cartesian product with itself
   *        :Reduce each pair by multiplication
     Í      :Sort
      â     :Deduplicate

```
> 1 votes

# Answer
# Factor \+ `math.matrices`, 43 bytes

```
[ [1,b] dup outer [ ] gather natural-sort ]

```

Try it online!

## Explanation

```
             ! 3
[1,b]        ! { 1 2 3 }
dup          ! { 1 2 3 } { 1 2 3 }
outer        ! { { 1 2 3 } { 2 4 6 } { 3 6 9 } }
[ ] gather   ! { 1 2 3 4 6 9 }
natural-sort ! { 1 2 3 4 6 9 }

```
> 1 votes

# Answer
# Arturo, 52 bytes

```
$[n][sort unique flatten map 1..n'x->map x..n=>[x*]]

```

Try it
> 1 votes

# Answer
# Thunno 2, 5 bytes

```
Ṗ€pUṠ

```

Try it online!

#### Explanation

```
Ṗ€pUṠ  # Implicit input
Ṗ      # Cartesian product
 €p    # Product of each
   U   # Uniquify the list
    Ṡ  # And sort it
       # Implicit output

```
> 1 votes

# Answer
## Google Sheets, 52 bytes

```
=SORT(UNIQUE(TOCOL(MAKEARRAY(N,N,LAMBDA(i,j,i*j)))))

```
> 1 votes

# Answer
## Python, ~~124~~ 102 bytes

```
n=input()
l=[1]
for i in range(1,n+1):
 for j in range(1,n+1):l.append(i*j)
print sorted(list(set(l)))

```

More pythonic!
> 0 votes

# Answer
# JavaScript (ES6), 86 bytes

```
n=>{n++;a=[];for(j=1;j<n;j++)for(i=1;i<n;i++)if(a.indexOf(i*j)<0)a.push(i*j);return a}

```

Looking to shorten it (maybe will try nesting loops).
> 0 votes

# Answer
# Perl 5, 91 bytes

```
for my $y (1 .. $ARGV[0]){
    map {$s{$n}++ unless($s{$n=$y*$_}) } ($y .. $ARGV[0])
}
print join(" ", sort {$a<=>$b} keys %s) . "\n";

```

to be run by passing the argument on the command line. It is quite a few declarations short of running with strictures and warnings.
> 0 votes

# Answer
# Perl 5, 67 bytes

```
for$i(1..($n=pop)){$a{$_*$i}++for 1..$n}map say,sort{$a<=>$b}keys%a

```
> 0 votes

# Answer
# Candy, 22 bytes

Input on stack

```
R0C(*=bA)bo(~Xe{|A?}x)

```

Long form:

```
range1
digit0
cart    # cartesian product of range0 and itself
while
  mult
  popA
  stack2
  pushA  # push products to second stack
endwhile
stack2
order
while    # loop to dedup
  peekA
  pushX
  equal
  if
    else
    pushA
    println
  endif
  XGetsA
endwhile

```
> 0 votes

# Answer
# Perl 5, 83 bytes

Here's a perl version that doesn't do a sort, and doesn't require duplicate removal. I'd like to claim that makes it faster, but it's running time is actually O(n^2.5)

`$n=pop;for$i(1..$n*$n){for$j(1+int(($i-1)/$n)..sqrt($i)){if($i%$j==0){say$i;last}}}`

A one-character longer and much slower version of this same approach reads as follows:

```
$n=pop;
for $i (1..$n*$n) {
  for $j (1..$i) {
    if ($i%$j == 0 && $i <= $n*$j && $i >=$ j*$j) {
      say $i;
      last
    }
  }
}

```

It works by traversing the multiplication table in a strictly ordered fashion.
> 0 votes

# Answer
# Prolog (SWI), 94 bytes

As the output only had to be in a reasonable format I've chosen to save 7 bytes by returning the list (which displays it), rather than doing an explicit write.
**Code:**

```
p(N,S):-findall(O,between(1,N,O),M),findall(Z,(member(X,M),member(Y,M),Z is X*Y),L),sort(L,S).

```

**Explained:**

```
p(N,S):-findall(O,between(1,N,O),M),                      % Get a list of numbers between 1 and N.
        findall(Z,(member(X,M),member(Y,M),Z is X*Y),L),  % Create a list of the products of the different combinations of elements in the list of numbers between 1 and N.
        sort(L,S).                                        % Sort and remove doubles

```

**Example:**

```
p(6,L).
L = [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 30, 36]

```

Try it out online here
> 0 votes

# Answer
# Jelly, 6 bytes, language postdates challenge

```
×þµFṢQ

```

Try it online!

There are so many different ways to do this in 6 bytes that it feels like 5 might be possible. I haven't found a way, though.

## Explanation

```
×þµFṢQ
×þ        Form multiplication (×) table (þ) up to the input
  µ       Fix a parsing ambiguity (µ in Jelly is like parentheses in C)
   F      Flatten the table into a single continuous list
    Ṣ     Sort the elements of the list
     Q    Take the unique elements of the sorted list

```
> 0 votes

# Answer
# Swift, ~~146~~ ~~137~~ ~~133~~ 87 bytes

```
var t={n in Set((1...n).map{i in(1...n).map{(i,$0)}}.joined().map{$0.0*$0.1}).sorted()}

```

To run, paste this into a playground or the REPL and call `t(_:)`.

Here's an expanded version:

```
func table(n: Int) -> [[Int]] {
   let range = 1...n

   let combos = range.map { i in
      range.map { j in
         (i, j)
      }
   }.joined()

   let products = combos.map { combo in
      combo.0 * combo.1
   }

   let uniques = Set(products)
   let sorted = uniques.sorted()
   return sorted
}

```

Let's run through this step by step. We'll assume that `n` is 4.

First, we create a closed range containing all the numbers from 1 to `n`, inclusive. So, `range` is set to `1...4`. (In the golfed version, it's more efficient to just create the range twice.)

Now we `map` over `range` twice, one `map` inside the other. This effectively creates a nested array containing every permutation of two numbers within the range `1...n`. We then join these arrays to remove the nesting. For our example, this sets `combos` to

```
[
   (1, 1), (1, 2), (1, 3), (1, 4),
   (2, 1), (2, 2), (2, 3), (2, 4),
   (3, 1), (3, 2), (3, 3), (3, 4),
   (4, 1), (4, 2), (4, 3), (4, 4)
]

```

(In actuality, it's a `FlattenSequence` instead of an `Array`, but that doesn't matter for what we're going to do with it.)

Next, we `map` over `combos`, returning the results of multiplying each tuple's elements together. (Using tuples instead of more arrays saves 2 bytes due to the shorter element access syntax.) This sets `products` to

```
[
   1, 2, 3, 4,
   2, 4, 6, 8,
   3, 6, 9, 12,
   4, 8, 12, 16
]

```

We then create a `Set` from this array. `Set`s are unordered, and can only contain one of each item. This enables us to concisely remove duplicate products, at the cost of losing the order of the products. For all intents and purposes, this sets `uniques` to

```
[1, 2, 3, 4, 6, 8, 9, 12, 16].shuffled()

```

Finally, we call `sorted()` on `uniques` to get our ordering back, and return the result, which is

```
[1, 2, 3, 4, 6, 8, 9, 12, 16]

```

By default, `sorted()` does the same thing as `sorted(by: <)`, which sorts in increasing order.
> 0 votes

# Answer
# Kamilalisp, 29 bytes

```
⊼∘⊙∘∊∘[$(⌼ *) #0 #0]∘$(+ 1)∘⍳

```

Attempt This Online!
> 0 votes

# Answer
# jq, 34 characters

```
[range(1;.+1)*range(1;.+1)]|unique

```

Sample run:

```
bash-5.2$ jq --compact-output '[range(1;.+1)*range(1;.+1)]|unique' <<< 5
[1,2,3,4,5,6,8,9,10,12,15,16,20,25]

```

(`range()` not generates array — “The numbers are produced as separate outputs.” Found no way to multiply a range's output by itself.)

Try it online!
> 0 votes

# Answer
# Scala, 57 bytes

Golfed version. Attempt This Online!

```
n=>(1 to n).flatMap(i=>(1 to n).map(i*_)).distinct.sorted

```

Ungolfed version. Attempt This Online!

```
def f(n: Int): Array[Int] = {
    // Construct a Range from 1 to the input
    val x = 1 to n

    // Compute the outer product of x with itself
    val o = for {
      i <- x
      j <- x
    } yield i * j

    // Get the unique elements and sort them
    o.distinct.sorted.toArray
}

```
> 0 votes

# Answer
# Perl 5 `-a`, 61 bytes

```
map{//;map$a{$'*$_}++,1.."@F"}1..$_;say for sort{$a-$b}keys%a

```

Try it online!
> 0 votes

---
Tags: code-golf, number, arithmetic
---


# Question
Title: Find all numbers between 2 and 100 co-prime to a given number
Your program will be given a number as input. Your challenge is to output all the numbers between 2 and 100 inclusive that are co-prime to the given number. (Two numbers are co-prime if their GCD is 1.) If no numbers between 2 and 100 are co-prime to the given number, the program shall not output anything.

The program must receive the number from STDIN, and the output must be a list of numbers separated by a comma and a space.

**Contest closes June 14th, 2014, two weeks from now. The shortest solution wins.**

Examples (here the range is from 2 to 20):

3:

```
2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20

```

12:

```
5, 7, 11, 13, 17, 19

```

9699690:

(No output: no numbers between 2 and 20 are co-prime to 9699690).

**EDIT:** Esoteric languages (e.g. J or GolfScript) are now being assessed separately from non-esoteric languages. This is to make the challenge fair.

# Answer
> 6 votes
# CJam, 23 bytes

```
101,:N2>q~mf{N%-}/", "*

```

Try it online. Paste the *Code*, type an integer in *Input* and click *Run*.

### Example

```
$ cjam factor.cjam <<< 210
11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97

```

### How it works

```
101,:N # Push the array [ 0 ... 100 ] and save it in “N”.
2>     # Remove 0 and 1 from the array.
q~mf   # Read from STDIN, interpret the input and factorize the resulting integer.
{      # For each prime factor:
  N%   # Collect all multiples of the prime factor in an array.
  -    # Apply set difference with the array on the stack.
}/     # This leaves only integers that are coprime with the input.
", "*  # Join by commas and spaces.

```

# Answer
> 4 votes
# Haskell, 76 characters

```
main=do n<-readLn;putStrLn.drop 2$[show k|k<-[2..100],gcd k n<2]>>=(", "++)

```

# Answer
> 3 votes
# GolfScript - 36

```
~:x;101,2>{.x{.@\%.}do;1>{;}*}%", "*

```

Explanation:

`~` evaluates the input to a number
`:x;` assigns the number to variable x
`101,2>` makes an array \[2 ... 100\]
`{...}%` applies the block to each array element, resulting in a modified array
`.x` duplicates the current number (from 2 to 100) then pushes x
`{.@\%.}do;` calculates the gcd (see the GolfScript home page)
`1>` checks if the gcd was greater than 1
`{;}*` executes the block if the condition was true; the block (`;`) pops the current number from the stack, thus taking it out of the array
`", "*` joins the resulting array using the ", " separator

# Answer
> 3 votes
# Python 2.7 - 87 bytes

```
from fractions import*
x=input()
print', '.join(`i`for i in range(2,101)if gcd(x,i)==1)

```

This is very similar to qwr's answer here, I shaved off some bytes but the changes were too substantial to fit in a comment. Full respect goes to them.

**Modifications:**

* Removed unnecessary space in `from fractions import *` for one byte.
* Moved the whole thing to python 2.7. I couldn't actually get the original answer to run on my machine because `input()` returns a string in python 3. The only thing that was specific to python 3 in the answer was defining the output format in the `print` function...
* ...which I changed anyway. The original answer looped through all the numbers and printed them out if the met the requirements. Here, I throw the whole thing in a generator function (with the output wrapped in backticks so we get a string) and `join` the numbers together, which saves bytes and means we don't have to use the "technically rules-valid" output format the original answer used (`23 ,29 ,31 ,37`... is a list of numbers separated by a comma and a space, but it doesn't waste any characters in my version to print out `23, 29, 31`... like the OP was probably expecting).

# Answer
> 3 votes
## Ruby, 52 46 (43 + 3 for " -p" option)

Now *does* beat it J (barely). Caveat: doesn't exit after outputting (you can actually keep giving more inputs after the first).

```
$_=(2..100).select{|w|w.gcd(eval$_)<2}*", "

```

# Answer
> 2 votes
# Julia - ~~70~~ ~~69~~ 68 characters

```
i=int(readline());print(join(find([gcd(i,x)<2 for x=2:100])+1,", "))

```

Saved a character by using a list comprehension rather than a map, pretty much thanks to not needing the dotted `.==`. I suspect that I can do better, still.

Second edit saved another character by using `<2` rather than `==1`, as gcd can't produce a number less than 1 (except when both inputs are 0, which cannot happen with this code), and must produce an integer.

Old version:

```
i=int(readline());print(join(find(map(x->gcd(i,x),2:100).==1)+1,", "))

```

Note that int is Int64 (assuming a 64 bit machine), meaning that you can't actually have a number big enough to be non-coprime to every number between 2 and 100. To have it accept arbitrary-size integers, you need to replace `int` with `BigInt`, for a total of 73 characters.

# Answer
> 2 votes
# Vyxal 3, 6 bytes

```
₅ḢΩ?ĠḂ

```

Try it Online!

RIP H flag

# Answer
> 1 votes
# JavaScript (ECMAScript 6) - 82 Characters

```
g=(a,b)=>b?g(b,a%b):a;f=x=>[k for(y in[...Array(99)])if(g(x,k=+y+2)<2)].join(', ')

```

**Explanation:**

Firstly a recursive function `g` to calculate the gcd:

```
g=(a,b)=>b?g(b,a%b):a;

```

Secondly, a function `f` taking a single argument `x`:

* `Array(99)` \- Start with an uninitialised array of length 99.
* `[...Array(99)]` \- Use the `...` spread operator to turn it into an array of 99 elements each initialised to `undefined`.
* `[+y+2 for(y in[...Array(99)])]` \- Use Array Comprehension to map the array of `undefined` values to an array of integers `2..100`.
* `[k for(y in[...Array(99)])if(g(x,k=+y+2)<2)]` \- Add an additional restriction to only include those values where `GCD(x,value)` is 1.
* `.join(', ')` \- at the end return it as a comma-space delimited string to meet the requirement of outputting nothing if there are no matches.

**Alternative**

Taking input from a prompt (87 characters):

```
x=prompt(g=(a,b)=>b?g(b,a%b):a);[k for(y in[...Array(99)])if(g(x,k=+y+2)<2)].join(', ')

```

# Answer
> 1 votes
# J (20):

Not quite complying with the rules as they are now, but hey... JS isn't either ;)

```
}.(1=a+.i.101)#i.101

```

Showcase:

```
   a=:3
   }.(1=a+.i.101)#i.101
2 4 5 7 8 10 11 13 14 16 17 19 20 22 23 25 26 28 29 31 32 34 35 37 38 40 41 43 44 46 47 49 50 52 53 55 56 58 59 61 62 64 65 67 68 70 71 73 74 76 77 79 80 82 83 85 86 88 89 91 92 94 95 97 98 100
   a=:12
   }.(1=a+.i.101)#i.101
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 79 83 85 89 91 95 97
   a=:9699690
   }.(1=a+.i.101)#i.101
23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

```

## Deconstruction:

Remember that J programs start at the back:

```
   i.101
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88...
   a=:12
   a+.i.101 NB. Takes GCD
12 1 2 3 4 1 6 1 4 3 2 1 12 1 2 3 4 1 6 1 4 3 2 1 12 1 2 3 4 1 6 1 4 3 2 1 12 1 2 3 4 1 6 1 4 3 2 1 12 1 2 3 4 1 6 1 4 3 2 1 12 1 2 3 4 1 6 1 4 3 2 1 12 1 2 3 4 1 6 1 4 3 2 1 12 1 2 3 4 1 6 1 4 3 2 1 12 1 2 3 4
   1=a+.i.101
0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0
   (1=a+.i.101)#i.101
1 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 79 83 85 89 91 95 97
   }.(1=a+.i.101)#i.101
5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 79 83 85 89 91 95 97

```

# Answer
> 1 votes
# Javascript (*ES5*) - 92 91

This solution runs in the Spidermonkey commandline shell. It takes input from STDIN (as per the rules).

```
with([])for(a=readline(b=1);b++<99||print(join(', '));--c||push(b))for(c=a,d=b;d;)d=c%(c=d)

```

Here is a solution that runs in the browser console and takes input from `prompt` and outputs with `alert`: **(89 bytes)**

```
with([])for(a=prompt(b=1);b++<99||alert(join(', '));--c||push(b))for(c=a,d=b;d;)d=c%(c=d)

```

If implicit printing in the browser console is allowed, it can go even further: **(82 bytes)**

```
for(o=[],a=prompt(b=1);b++<99;--c||o.push(b))for(c=a,d=b;d;)d=c%(c=d);o.join(', ')

```

# Answer
> 1 votes
## Haskell - 105

```
import Data.List
main=do
 x<-getLine
 putStrLn.intercalate", ".map show$filter((1==).gcd(read x))[2..100]

```

Quite obvious if you can understand Haskell. :)

# Answer
> 1 votes
# Lua, 126

Now it's 2 times longer, but it actually works.

```
c=io.read()function g(a,b)return b~=0 and g(b,a%b) or tonumber(a) end for i=2,100 do if g(i,c)<2 then io.write(i,', ') end end

```

---

# Lua, 63

Not much better, but still...

```
c=io.read()for i=2,100 do if i%c>0 then io.write(i,', ')end end

```

# Lua, 64

```
c=io.read()for i=2,100 do if i%c>0 then io.write(i..', ')end end

```

# Answer
> 1 votes
## Pyke, 9 bytes (noncompeting)

```
TXSt#.H1q

```

Try it here!

```
TX        -   10**2 (100)
  St      -  range(2, ^)
    #     - filter(^, V)
     .H   -   highest_common_factor(i, input)
       1q -  ^ == 1

```

# Answer
> 1 votes
# Vyxal `H`, 44 bitsv2, 5.5 bytes

```
ɽḢ'?ġ1=

```

Try it Online!

Bitstring:

```
00100110011110110000000000001000100000100111

```

Because vyxal 3 is missing a lot of numerical operations :p

# Answer
> 1 votes
# Japt, 7 bytes

```
Lõ ÅfjU

```

Try it here

# Answer
> 0 votes
## Sage, 79

A boring answer, since I'm not in the mood of writing an interesting one.

```
l=[]
n=input()
for i in range(2,101):
 if gcd(i,n)==1:l+=[i]
print str(l)[1:-1]

```

Sample outputs:

```
sage: %runfile coprimelist.py
3
2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26, 28, 29, 31, 32, 34, 35, 37, 38, 40, 41, 43, 44, 46, 47, 49, 50, 52, 53, 55, 56, 58, 59, 61, 62, 64, 65, 67, 68, 70, 71, 73, 74, 76, 77, 79, 80, 82, 83, 85, 86, 88, 89, 91, 92, 94, 95, 97, 98, 100
sage: %runfile coprimelist.py
12
5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, 53, 55, 59, 61, 65, 67, 71, 73, 77, 79, 83, 85, 89, 91, 95, 97
sage: %runfile coprimelist.py
9699690
23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
sage: %runfile coprimelist.py
factorial(100)

sage:

```

# Answer
> 0 votes
# python - 90

Boring answer. The output is a little strange (but meets the rules)

```
from fractions import *
x=input()
for i in range(2,101):
 if gcd(x,i)==1:print(i,",",end="")

```

# Answer
> 0 votes
# J - 47 char

Requiring input on STDIN (no trailing newlines, please) and outputting to STDOUT in proper form.

```
(2}.&;(2+i.99)(', ';":)&>@([#~1=+.)".)&.stdin''

```

`2+i.99` is the integers from 2 to 100 inclusive. `([#~1=+.)` keeps only those integers coprime to the input, and then `(', ';":)` converts each (`&>`) to a string and adds the comma and space before each entry. `;` combined the entire result into a single string, and `2}.` drops the comma and space before the first one.

# Answer
> 0 votes
# ised (28)

```
ised '@1{6};' '?{{:gcd{x$1}:}@::[101]<2}\1'

```

The first argument is just setting the argument (6 in this case). The second evaluates the result.

With unicode, it's a bit shorter (26).

```
ised '@1{6};' '?{{:gcd{x$1}:}∷[101]<2}\1'

```

Unfortunately, the braces take up a lot of space in ised because it's not stack-based.

# Answer
> 0 votes
# wxMaxima: ~~67~~ ~~85~~ 80

I had to adjust my answer to fit the specs (i.e., take a value from stdin)

```
f():=block(n:read(),for i:2thru 100 do if(gcd(i,n)=1)then printf(true,"~d, ",i) )

```

Call this in the interactive session via `f` and then enter in your value followed by `ctrl+enter` to get the result.

---

Old, non-spec fitting answer

```
f(n):=for i:1thru 100 do(if(gcd(i,n)=1)then printf(true,"~d, ",i));

```

Enter this into the command line & execute it via `f(12);` to get

```
1,5,7,11,13,17,19,23,25,29,31,35,37,41,43,47,49,53,55,59,61,65,67,71,73,77,79,83,85,89,91,95,97,

```

# Answer
> 0 votes
# Python 3 - 79 chars

```
x=int(input())
for i in range(2,101):print(i) if pow(x,i-1,i)==1or i==x+1else 0

```

Uses the Fermat primality test to check co-primes.

# Answer
> 0 votes
# APL(NARS), 35 chars

```
5↓∊(⊂', '){⍺⍵}¨' ',⍕¨a⊂⍨1=⎕∨a←1+⍳99

```

use as:

```
  5↓∊(⊂', '){⍺⍵}¨' ',⍕¨a⊂⍨1=⎕∨a←1+⍳99
⎕:
  2310
┌78─────────────────────────────────────────────────────────────────────────────┐
│ 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97│
└───────────────────────────────────────────────────────────────────────────────┘

```

# Answer
> 0 votes
# Tcl, 218 bytes

Golfed version. Attempt This Online!

```
proc gcd {a b} {while {$b} {set t $b; set b [expr {$a % $b}]; set a $t}; return $a}
set n [expr {[gets stdin]}]
set r [list]
for {set k 2} {$k <= 100} {incr k} {if {[gcd $n $k] == 1} {lappend r $k}}
puts [join $r ", "]

```

Ungolfed version. Attempt This Online!

```
proc main {} {
    # Read a number from input
    set n [gets stdin]

    # Initialize an empty list to store the numbers
    set numbers {}

    # Loop through numbers 2 to 100 and check if gcd with n is less than 2
    for {set k 2} {$k <= 100} {incr k} {
        # Check if the gcd of k and n is 1 (coprime)
        if {[gcd $k $n] < 2} {
            # If so, append k to the list of numbers
            lappend numbers $k
        }
    }

    # Join the numbers with a comma and a space, and then print
    puts [join $numbers ", "]
}

proc gcd {a b} {
    # Calculate the greatest common divisor of a and b
    while {$b != 0} {
        set temp $b
        set b [expr {$a % $b}]
        set a $temp
    }
    return $a
}

# Call the main procedure
main

```

---
Tags: code-golf, math
---