Write the shortest snippet of code possible such that, when N copies of it are concatenated together, the number of characters output is N2. N will be a positive integer.

For example if the snippet was soln();, then running soln(); would print exactly 1 character, and running soln();soln(); would print exactly 4 characters, and running soln();soln();soln(); would print exactly 9 characters, etc.

Any characters may be in the output as long as the total number of characters is correct. To avoid cross-OS confusion, \r\n newlines are counted as one character.

Programs may not read their own source or read their file size or use other such loopholes. Treat this like a strict challenge.

The output may go to stdout or a file or a similar alternative. There is no input.

Comments in the code are fine, as is exiting mid-execution.

Any characters may be in the program. The shortest submission in bytes wins.

  • \$\begingroup\$ Does the program have to terminate? \$\endgroup\$ – Martin Ender Feb 5 '15 at 17:57
  • \$\begingroup\$ @MartinBüttner Yes \$\endgroup\$ – Calvin's Hobbies Feb 6 '15 at 0:07

24 Answers 24


TECO, 4 bytes


V prints the contents of the current line in the text buffer. 1\ inserts the string representation of the number 1 at the current position.

So on the Nth iteration of the program, the first V will output N - 1 copies of the character 1, then add another 1 to the text, then output N 1s.

  • 1
    \$\begingroup\$ Can you add a link to TECO? \$\endgroup\$ – Erik the Outgolfer Aug 22 '17 at 10:57

Brainfuck, 17 16 bytes


You can test it here. Just use the fact that n2+2n+1=(n+1)2.

  • 16
    \$\begingroup\$ I can't believe I'm seeing BF at a competitive level of bytes! \$\endgroup\$ – agweber Feb 5 '15 at 14:52

Brainfuck, 11

I saw the first Brainfuck answer and thought it's way too long :)


The output may be easier to see if you replace the plus with a lot more pluses.

On the Nth iteration, each loop outputs N - 1 copies of the character with ASCII value 1, and then one more with +..

  • \$\begingroup\$ You need to print N^2 characters, not N characters. I can't read BF code, so I don't know if your code is incorrect or if your description is incorrect. \$\endgroup\$ – Brian J Feb 6 '15 at 14:35
  • \$\begingroup\$ @BrianJ It prints N^2 characters. You can test it here: copy.sh/brainfuck Replace the plus with a minus if you can't see the output. \$\endgroup\$ – alephalpha Feb 6 '15 at 14:59
  • \$\begingroup\$ @alephalpha Oops, I now see that I misread the comment. The code does not do (N - 1) + 1 like I originally thought. \$\endgroup\$ – Brian J Feb 6 '15 at 15:02

Python 2, 22

a='';print a;a+='xx';a

Prints the empty string, then two x's, then x' four and so on. With the newline after each string, this comes out to n*n characters.

One copy: "\n" (1 char)
Two copies: "\nxx\n" (4 chars)
Three copies: "\nxx\nxxxx\n" (9 chars)

In order to stop the initial variable a from being reinitialized each run, I end the code with a ;a, which is benign on its own, but combined with the next loop to create the scapegoat aa to be assigned instead. This trick isn't mine; I saw it in a previous answer. I'd appreciate if someone could point me so I could give credit.

  • \$\begingroup\$ Actually, is the final newline printed? \$\endgroup\$ – xnor Feb 5 '15 at 7:06
  • \$\begingroup\$ no I don't think the final newline is printed. But simply removing the , after print a should work. print a prints a newline after each print. \$\endgroup\$ – Justin Feb 5 '15 at 7:38
  • \$\begingroup\$ @Quincunx Oh, of course, thanks! \$\endgroup\$ – xnor Feb 5 '15 at 7:40
  • \$\begingroup\$ Are you talking about this post? \$\endgroup\$ – Sp3000 Feb 5 '15 at 8:02

CJam, 6 bytes


Uses the fact that n2 + n + (n+1) = (n+1)2.

L      "Push L. Initially this is an empty string, but its length increases by 1 with each copy
        of the snippet.";
 L     "Push another L.";
  S+   "Add a space to the second copy.";
    :L "Store the lengthened string in L for the next copy of the snippet.";
  • \$\begingroup\$ :L..1+ is the same idea in GolfScript. \$\endgroup\$ – Peter Taylor Feb 5 '15 at 10:10
  • \$\begingroup\$ @PeterTaylor I was thinking ..n+ in GolfScript, but that pesky trailing newline... :( \$\endgroup\$ – Martin Ender Feb 5 '15 at 10:13
  • \$\begingroup\$ Hah, you're right. No need for :L because it's not used. \$\endgroup\$ – Peter Taylor Feb 5 '15 at 10:25

///, 21 bytes

I'm sure there is a really short and twisted way to solve this in /// but I couldn't find anything, beyond the "straightforward" way yet:


This is based on the approach of printing consecutive odd numbers. The snippet consists of a 1 at the start which is printed, and two replacements which add two more 1s to that first part of each consecutive copy of the snippet. Let's go through this for N = 3. The following should be read in groups of 3 or more lines: 1. the current code, 2. the processed token(s), 3. (and following) a comment what the above token does.

is printed
replaces all occurrences of 1/ with 112/. This affects the starts of all further snippets
but not the substitution commands, because the slashes in those are always escaped.
It is necessary to put a 2 in there, because otherwise the interpreter goes into an infinite
loop replacing the resulting 1/ again and again.
Replace all occurrences of 2/ with 1/, so the the next snippets substitution works again.
is printed
add two 1s again
turn the 2 into a 1 again
print 11111
the last two substitutions have nothing to substitute so they do nothing

Interestingly, it works just as well if we move the 1 to the end:


><>, 14 bytes


Uses the "sum of consecutive odd integers starting from 1" idea. It starts off with 1 and multiplies it by 100 each time, increasing the length of the output progressively by increments of 2.

For example, appending 5 copies gives


I tested by piping the output to a file, and didn't see a trailing newline.


1                   Push 1, skipped by ! every time except the first
 :n                 Copy top of stack and output as num                  
   a*a*             Multiply by 10 twice
       ';'10p       Modify the source code so that the first : becomes a ; for termination
             !      Skip the next 1

CJam, 10 9 bytes


This prints N2 spaces where N is the number of copies of the code.

Code eexpansion:

],            "Wrap everything on stack and take length";
  )_          "Increment and take copy";
    S*        "Get that length space string";
      a*      "Wrap that space string in an array and create that many copies";
        ~     "Unwrap so that next code can use to get length";

Try it online here


Python 2, 20 bytes


Java - 91 bytes

{String s=System.getProperty("a","");System.out.println(s);System.setProperty("a","xx"+s);}

This solution is equivalent to this other one in Python. It surely won't win, but it was fun :)

  • \$\begingroup\$ Don't you need a class to run anything? \$\endgroup\$ – user32377 Feb 6 '15 at 8:55
  • \$\begingroup\$ No, since OP asked for snippets of code. We can assume this is running inside a main, for example. \$\endgroup\$ – cygnusv Feb 6 '15 at 9:21
  • \$\begingroup\$ Then I have a 59 or even 44 byte solution. \$\endgroup\$ – user32377 Feb 6 '15 at 9:24
  • \$\begingroup\$ Cool :) I prefer one-liners, but yours is indeed shorter! \$\endgroup\$ – cygnusv Feb 6 '15 at 9:36

Perl, 14 bytes


This needs to be run with Perl's -l command switch, which causes print to append new lines.

It prints the default variable $_, then prepends two underscores via substitution.


$ perl -le 'print;s//__/;print;s//__/;print;s//__/;print;s//__/;'

  • \$\begingroup\$ flags are counted as 1 more byte per flag \$\endgroup\$ – Optimizer Feb 5 '15 at 10:59
  • \$\begingroup\$ What about say? \$\endgroup\$ – hmatt1 Feb 6 '15 at 22:55
  • \$\begingroup\$ @chilemagic I tried that, but I couldn't get it working on my versions of Perl. \$\endgroup\$ – grc Feb 7 '15 at 1:08
  • \$\begingroup\$ @grc it's version 5.10 and higher and you need -E instead. \$\endgroup\$ – hmatt1 Feb 7 '15 at 1:37
  • \$\begingroup\$ @chilemagic hmm, that didn't seem to work for me on 5.16. \$\endgroup\$ – grc Feb 7 '15 at 7:52

Brainfuck, 10 chars

Both previous Brainfuck solutions were waaay too long (16 and 11 chars) so here is a shorter one:


In the n-th block it prints out 2*n-1 characters (with codepoints from 2*n-1 to 1)

  • 2
    \$\begingroup\$ This wouldn't work in standard brainfuck, only if the cells are unlimited-size. Actually, it wouldn't totally make sense then either. How do you output character code 1 trillion? \$\endgroup\$ – feersum Feb 8 '15 at 23:28

Prelude, 18 12 bytes


This prints N2 tabs. It assumes a standard-compliant interpreter which prints characters instead of numbers, so if you use the Python interpreter you'll need to set NUMERIC_OUTPUT to False.

The idea is simply to use the top of the stack (which is initially 0) as 2(N-1), and print 2N-1 tabs, then increment the top of the stack by 2. Hence each repetition prints the next odd number of tabs.


Java - 59 / 44 (depending on requirements)

static String n="1";

Apparently we're allowed to assume code runs in a class.

If it can go inside a main method:

String n="1";

C, 87 bytes

#include __FILE__

This uses two magic macros. __COUNTER__ is a macro that expands to 0 the first time it is used, 1 the second, etc. It is a compiler extension, but is available in both gcc, clang, and Visual Studio at least. __FILE__ is the name of the source file. Including a file in C/C++ is literally the same as pasting it directly into your source code, so it was a little tricky to make use of.

It would still be possible to use this technique without __COUNTER__. In that case, the standard guard against using code twice could be used for the #if statement, and __LINE__ could be used to count the number of characters needed.

  • \$\begingroup\$ This solution is not written in C, but rather a C dialect. Please correct the language name. \$\endgroup\$ – FUZxxl Feb 5 '15 at 12:41
  • 2
    \$\begingroup\$ @FUZxxl Most code-golf answers are only designed to work in gcc, so I'm not sure why this would be an issue. \$\endgroup\$ – feersum Feb 5 '15 at 13:31
  • \$\begingroup\$ It isn't, but you should really declare that. \$\endgroup\$ – FUZxxl Feb 5 '15 at 13:36
  • \$\begingroup\$ I'm confused. Why declare a non-issue? O_o \$\endgroup\$ – corsiKa Feb 5 '15 at 16:25
  • \$\begingroup\$ @corsiKa It's only a non-issue if you declare it. The C gcc speaks is not standard C. \$\endgroup\$ – FUZxxl Feb 6 '15 at 1:06

Dyalog APL, 20 19 bytes

A matrix based solution.


Try it here. Returns a string of N2 repetitions of a. Explanation by explosion for N = 2:

                                  ⍪'a'  Wrap 'a' into a 1x1 matrix.
                'a'{            }⍨      Binary function: bind 'a' to ⍵ and the matrix to ⍺.
                    ⍺≢⍵:                The arguments are not identical,
                        ⍵⍪⍵,⍺           so add to the matrix 1 column and 1 row of 'a's.
               ⍪                        Identity function for a matrix.
{            }⍨                         Unary function: bind the matrix to both ⍵ and ⍺.
 ⍺≢⍵:                                   The arguments are identical,
           ∊⍺                           so flatten the matrix into the string 'aaaa'.


di _n($a)
gl a=$a+2

There is a trailing new line to make sure that the display (di) statement works. First display the current number in $a newlines (and one additional from the default of display). Then add 2 to $a.

Uses the even numbers approach (i.e. odd numbers approach minus 1) with an extra newline every time.


T-SQL 117


Note the trailing space to ensure that the if condition is properly checked every time.

Uses the odd numbers approach. Not sure if there's a newline on select statements.

Not sure if there's a shorter way to create a table if it doesn't exist.

  • 2
    \$\begingroup\$ Kudos to you for an unusual language choice. \$\endgroup\$ – Xynariz Feb 5 '15 at 19:56

PostScript, 35 chars

count dup 2 mul 1 add string print

Each pass "leaks" one thing on the stack, so count goes up by 1 each time. Then it justs uses the sum of odd numbers trick.

The bytes output are all \000 because that's the initial value of strings.


Haskell, 72

putStr$let a="1";aputStr=(\n->take(n^2)$show n++cycle" ").(+1).read in a


The apply operator $ acts as if you place surrounding parentheses around the rest of the line (there are exceptions to this, but it works in this case). aputStr is a function that takes a string with the format "abc ...", where "abc" is the square root of the length of the string, including abc. It will parse the string as an integer, and return a string starting with abc+1 and having that length squared. Because of the $ operator, this will get called recursively on "1" N times.


Pyth, 8 bytes


This relies on the fact that N2 is equal to the sum of N odd numbers. Now Pyth auto prints an new line, so I have to just print Z * 2 characters in each code where Z goes from 0 to N - 1.

Code Expansion:

*d               "Print d whose value is a space character"
  *2Z            "2 * Z times where Z's initial value is 0"
     ~Z1         "Increment the value of Z";

Try it online here


Golflua, 23 bytes


outputs a combination of & and \n characters.

Equivalent Lua code

X = 2 + (X or -2)          -- initialize X to 0 the first time, add 2 ever other time

print(string.rep("&", X))

Each time the code snippet runs it produces 2 more characters of output than the last time, starting with 1 character. The print function appends a newline, so I initialize X to 0 instead of 1.


ActionScript - 27 / 26 bytes

var n=""


var n=1

How it works:

var n=""
trace(n);n+="11"//var n=""

It simply comments out the first line. Note: trace adds a newline. Or maybe all the IDE's I use do that automatically.


GML, 27


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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