Write a program that counts up forever, starting from one.


  • Your program must log to STDOUT or an acceptable alternative, if STDOUT is not available.
  • Your program must be a full, runnable program, and not a function or snippet.
  • Your program must output each number with a separating character in between (a newline, space, tab or comma), but this must be consistent for all numbers.
  • You may print the numbers in decimal, in unary or in base 256 where each digit is represented by a byte value.
  • Your program must count at least as far as 2128 (inclusive) without problems and without running out of memory on a reasonable desktop PC. In particular, this means if you're using unary, you cannot store a unary representation of the current number in memory.
  • Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.

    Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

  • This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.


The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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 snippet:

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

<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution 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> <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> <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><script>var QUESTION_ID = 63834; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 39069; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(42), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>

  • 31
    \$\begingroup\$ I'm not sure how to combine must output each number with a separating character in between with may print the numbers [...] in base 256. \$\endgroup\$
    – Dennis
    Nov 14 '15 at 14:25
  • 7
    \$\begingroup\$ For future challenges, may I recommend the sandbox such that all these details could be sorted out before people start posting answers? :) \$\endgroup\$ Nov 14 '15 at 14:32
  • 3
    \$\begingroup\$ @IlmariKaronen I interpret that as being a memory limit, not a time limit. possibly a time limit on per-increment. just set the counter to 2**128-10 and see how long it takes to take those last ten steps. \$\endgroup\$
    – Sparr
    Nov 15 '15 at 7:41
  • 5
    \$\begingroup\$ Can we have leading zeroes in the output? \$\endgroup\$ Nov 15 '15 at 11:43
  • 4
    \$\begingroup\$ Ugh!!! I have an answer for TI-89 (56b), but I can't post b/c I'm new to the site and don't have Rep 10+! \$\endgroup\$ Nov 15 '15 at 20:45

198 Answers 198

3 4 5

Turing Machine Simulator, 536 bytes

a * * r a
a , * r A
A * * r A
A , * l b
b * * l b
b , * l c
b s 0 l 0
b p 1 l 1
b d 2 l 2
b f 3 l 3
b g 4 l 4
b h 5 l 5
b i 6 l 6
b j 7 l 7
b k 8 l 8
b l 9 l 9
0 * * l 0
0 _ s r a
1 * * l 1
1 _ p r a
2 * * l 2
2 _ d r a
3 * * l 3
3 _ f r a
4 * * l 4
4 _ g r a
5 * * l 5
5 _ h r a
6 * * l 6
6 _ i r a
7 * * l 7
7 _ j r a
8 * * l 8
8 _ k r a
9 * * l 9
9 _ l r a
c _ p l d
c s p l d
c p d l d
c d f l d
c f g l d
c g h l d
c h i l d
c i j l d
c j k l d
c k l l d
c l s l c
d * * l d
d _ , r A

Test it out here -> link
initial input: ,*p,
initial state: b

state a: move right until a comma is found then move to state A
state A: move right until a comma is found then move to state b
state b: move left until a letter or a comma is found. If a letter is found, change the letter to its corresponding digit and move to the corresponding state. If a comma is found, move to state c.
states 0-9: move left until an empty space is found then write the digit
state c: increment the number and end up on the left then move to state d
state d: place a comma then move to state A

Basically, it finds the previous number, copies it over while converting it to digits, increments it, then starts all over.

On a real turing machine this would go way over 2^128

  • \$\begingroup\$ You could save some bytes by converting this to use binary, I'm not sure whether or not that would improve speed any though \$\endgroup\$ Feb 2 '16 at 15:49
  • \$\begingroup\$ Not sure if binary is allowed in the rules, but unary would definitely be shorter \$\endgroup\$ Feb 2 '16 at 15:51
  • \$\begingroup\$ My BotEngine answer uses binary, at least. \$\endgroup\$ Feb 2 '16 at 16:00
  • \$\begingroup\$ The initial input can just be ,p, . Don't need the asterisk. \$\endgroup\$
    – ouflak
    Dec 4 '20 at 20:59

BotEngine, 128 120 112 8x13=104

v2 2 01
>e>S SS
   e2 e0 12
   > > S SS P
  ^   <e0e1 R
     ^ < <lC^
^         <

Output is in binary.


05AB1E, 4 bytes



[           # start infinite loop
 ¼          # increase counter
  ¾         # push counter
   ,        # print with a newline
  • 1
    \$\begingroup\$ ASCII-only version: [N>, \$\endgroup\$ Aug 22 '17 at 15:12
  • \$\begingroup\$ Another 4-bytes alternative: 0[>= \$\endgroup\$ Mar 5 '19 at 14:21

C, 93

Count up to 10^97. Add 3 bytes to count up to 10^997 (and so on).


Less golfed


    if(*q > '8') {
      *q = '0';
    else {
      if (!*q) {
        *q = '0';
        p = q; 
      q = d + 97;

Acc!, 64 65 bytes

Also works in Acc!!.

Count q while 1 {
Count x while q-x+1 {
Write 7
Write 9

This prints the numbers out in unary using Bell characters seperated by tabs. If I have to use a more standard character, that would make the program 66 bytes.

The Acc! interpreter provided in the linked answer translates Acc! to Python, which does support arbritrary-precision integers.


Racket, 40 bytes

(sequence-for-each println(in-naturals))

Racket has arbitrary-precision numbers, so this will continue to count up forever.


Scala, 41 39 35 bytes


Other versions (I left all solutions there because they're significantly different):

def r(n:BigInt){println(n);r(n+1)};r(0)   // 39
var i=BigInt(0);while(1>0)println{i+=1;i} // 41

This is my first time writing Scala code.

Original idea based on SuperJedi224's Java answer.

{i=>i+1} can be shortened to {_+1}.
foreach println was replaced with print because the problem description allows any separator.
Iterator.iterate and Stream.iterate, though completely different, do the same thing.

Other tries

Stream.from(0).print() // overflows at Integer.MAX_VALUE
BigInt(0).to(10)foreach println // 10 should be BigInt.MAX_VALUE (=Infinity), which doesn't exist
def from(start:BigInt):Stream[BigInt]=Stream.cons(start,from(start+1));from(0).print // too long
  • \$\begingroup\$ Shouldn't println(i+=1) work just as well? \$\endgroup\$
    – Bergi
    Nov 14 '15 at 22:26
  • 1
    \$\begingroup\$ @Bergi no, assignments are not expressions in Scala: their type is Unit (void). I learned that the hard way by trying what you suggest, but REPL outputted (). See for example this on SO. This is the shortest version I could come up with based on this answer. Notice that also there's no increment (++i) operator for BigInts. \$\endgroup\$
    – TWiStErRob
    Nov 14 '15 at 22:37
  • \$\begingroup\$ Oh right. Sure, assignment is evil in Scala. More functional would be something like Stream.from(1).forEach(printLn _) I guess, but Stream.from seems to leak memory and not work with BigInts. \$\endgroup\$
    – Bergi
    Nov 14 '15 at 22:59
  • \$\begingroup\$ @Bergi added all my other tries to the answer. \$\endgroup\$
    – TWiStErRob
    Nov 14 '15 at 23:06

C, 95 bytes

int a,c[50]={-38};main(){for(a=49;++c[a]>9;c[a--]=0);for(a=0;a<50;++a)putchar(c[a]+48);main();}


  • \$\begingroup\$ This recurses, not sure if the stack will hold 2^128 call frames.. \$\endgroup\$
    – Kenney
    Nov 15 '15 at 18:30
  • 3
    \$\begingroup\$ Tail-call optimization will take care of it, so it's no problem. Moreover, the C standard doesn't limit the stack size. \$\endgroup\$
    – Lynn
    Nov 15 '15 at 19:36

Perl 6, 13 bytes

.say for 1..*

8086 machine code + DOS, 34 bytes


30 0D 0A 24 FE C6 BB 00 01 B4 09 CD 21 FE 07 80
3F 3A 75 F2 C6 07 30 4B 3B DA 73 F1 C6 07 30 4A

In assembly language:


    org 100h


    db '0',13,10,'$' ; output buffer
    inc dh ; assign dx=0x100 - address of the output buffer

    mov bx, 100h
    mov ah, 9
    int 21h ; print the number

    inc byte ptr [bx]
    cmp byte ptr [bx], '0'+10
    jne increase_num
    mov byte ptr [bx], '0'
    dec bx
    cmp bx, dx
    jae increase_digit
    mov byte ptr [bx], '0'
    dec dx
    jmp increase_digit


Some explanations:

Output buffer is at offset 0x100; it contains 4 bytes at first: '0', a newline sequence 0d 0a, and '$', which is an end-of-output-buffer byte that DOS uses. These 4 bytes are executed as nonsensical code:

xor [di],cl
or ah,[si]

This destroys the program exit instruction at offset 0, but this is OK because the program will not exit!

The instruction inc dh generates the value 0x100 in dx, which is the address of the output buffer. The output buffer grows down, decreasing the value of dx with each power of 10.

The number is stored as an ASCII string. The increment code starts from the last digit, increases it and checks whether it went out of range 0...9. If yes, it sets the digit to 0 and goes to the next digit (dec bx). If all digits are set to 0, it adds (dec dx) another 0 digit, and immediately increases it to 1.

  • \$\begingroup\$ I realize this is an old answer but I'm curious: How can you assume dx and di are zero-initialized? As far as I know their values are undefined on entry. \$\endgroup\$ Apr 24 '17 at 6:17

O, 7 bytes



1       Pushes 1 to the stack
 {   }w While the top of the stack is not 0
  .o)   Output the top of the stack and increment it

Does not work on online IDE, but does in REPL and file.


Burlesque, 9 bytes


If you don't care what the first character is go with 1R@.


R@ is the RangeInf built-in and creates a Block with numbers [N..Infinity] so 1R@ generates a Block {1 2 3 4 5....}. However, if we display this we'll have a { at the start of our output which we don't want. SH converts a value to a display value (called Pretty) and then back to a String using the display format. 2 is the Format With Spaces so 2SH produces [1 2 3 4 5...]. Now we use [- which is the Tail built-in which removes the first character in that string. Q converts our string to a display value. Burlesque generally prints things as you input them, so when it prints a String there it will be surrounded by quotes. If one doesn't want that we have to convert it to a display value (called Pretty).

blsq ) "hi"
blsq ) "hi"Q
blsq ) 5ro
{1 2 3 4 5}
blsq ) 5ro2SH
"[1 2 3 4 5]"
blsq ) 5ro2SH[-
"1 2 3 4 5]"
blsq ) 5ro2SH[-Q
1 2 3 4 5]
  • \$\begingroup\$ BTW: Technically this displays a list as string with the first character removed. So it displays '1 2 3 4 5 ......]' but since it's infinite in size ']' will never be printed. \$\endgroup\$
    – mroman
    Nov 14 '15 at 13:29
  • \$\begingroup\$ Could you explain this code char by char? I tried the doc, but there's no easy way of searching. \$\endgroup\$
    – vrwim
    Nov 14 '15 at 23:35
  • 1
    \$\begingroup\$ I've added an explanation. \$\endgroup\$
    – mroman
    Nov 16 '15 at 10:26

sed, 116 92 83 bytes


Usage: Sed operates on text input and it needs input do anything. To run the script, feed it with just one empty line:

$ echo | sed -f forever.sed

Explanation: To increment a number, the current number is split up into a prefix and a suffix where the suffix is of the form [^9]9*. Each digit in the suffix is then incremented individually, and the two parts are glued back together. If the current number consists of 9 digits only, a 0 digit is appended, which will immediately incremented to a 1.


Powershell, 43 29 bytes


Relies on .Net 4.0 and up for System.Numerics.BigInteger



Thanks to TimmyD for the additional tips for use of parens to a automatically produce output and [bigint] for type assignment.

  • 1
    \$\begingroup\$ Welcome to PPCG! If you use PowerShell v4+, you can use the [bigint] alias instead of [Numerics.BigInteger]. Additionally, enclosing the variable in parens will automatically produce output, and using the inline ++ instead of assignment shortens as well. Results in [bigint]$i;for(){($i++)} for 24 Bytes. \$\endgroup\$ Nov 16 '15 at 14:06
  • \$\begingroup\$ @TimmyD Thanks for the tips! I'm using PowerShell 5.0, but couldn't use just [bigint]$i without getting an error. Ran into a few other gotchas with going with just ($i++). I can list them if it would be appropriate. \$\endgroup\$
    – Booga Roo
    Nov 16 '15 at 21:04
  • \$\begingroup\$ Interesting. v5 (or the behind-the-scenes .NET) must have updated/changed default initializations and/or the ++ operator overload. \$\endgroup\$ Nov 16 '15 at 21:21
  • \$\begingroup\$ For v5, you can still do for([BigInt]$i=0){($i+=1)} for 25 bytes \$\endgroup\$
    – Veskah
    Jul 12 '19 at 13:08

PARI/GP, 23 bytes


Sample Usage

$ gp -qf < countup.gp

Brainfuck, 44 bytes


I'm surprised there are no brainfuck submissions, so here's my attempt (and my first brainfuck program). I interpreted the constraint on number formatting as 'whatever is convenient for your language', so the output here is as a binary string of 00 and 01, with FF as separators. The beginning of the output:

0000000: 01 ff 01 00 ff 01 01 ff 01 00 00 ff 01 00 01 ff  ................
0000010: 01 01 00 ff 01 01 01 ff 01 00 00 00 ff 01 00 00  ................

The standard 30000 byte BF implementation can go as high as 2^15000 before reaching undefined behavior. Here is another version which produces a more readable output consisting of "0" and "1" with newlines as separators (currently 105 chars, although this can probably be golfed more):




Mathematica, 22 bytes


Seriously, 4 bytes



1    puts 1 on the stack
W    begins a while loop that executes while the (peeked) value on top of the stack is truthy
  ■    output entire stack without popping
  u    increment value on top of stack
<EOF> implicit end of while loop block

No online interpreter link because it doesn't do so well with infinite loops.


Pyth, 4 bytes


.V begins an infinite loop which defines incremented b, starting with 1. The body of the loop implicitly prints b on the next line.


dc, 12 bytes

Uses an "anonymous" recursive macro, should be able to run for ever:

  • 1
    \$\begingroup\$ For once, bc is shorter \$\endgroup\$ Nov 14 '15 at 21:17
  • \$\begingroup\$ The 11-byte solution is invalid: you cannot store a unary representation of the current number in memory. And besides it starts from 0 rather than from 1. \$\endgroup\$
    – user46915
    Nov 16 '15 at 11:57

WhoScript, 28 27 bytes

1#1;v;e;pw #;#a;pw;#1;+;i;d


# 1                        @ push 1 to the stack
time_vortex                @ begin an infinite loop
  duplicate                @ duplicates the top of the stack
  psychic_paper write #    @ prints the top of the stack as a number
  # a                      @ pushes 10 (0xA) to the stack
  psychic_paper write      @ prints the character whose ASCII code matches the top of the stack
  # 1                      @ pushes another 1 to the stack
  +                        @ adds the top two stack values (as a floating point number)
  integer                  @ converts the top number of the stack to an integer
paradox                    @ go back to the 'time_vortex' line

Shaved off a byte by using 0xA instead of 0x20


Fuzzy Octo Guacamole, 4 bytes



(  )    # Infinite loop.
 +      # Increment ToS, which is 0 by default.
  X     # Print ToS.
        # Implicit output applies to the end of a loop.
  • \$\begingroup\$ This is a catalogue, not a challenge, so no problem submitting when the language is newer than the question \$\endgroup\$
    – vrwim
    Apr 25 '16 at 14:19

Sesos, 2 bytes


0000000: 0c3a                                              .:

Try it online!


set numout ;output one number per line instead of character
nop        ;set entry marker (start of loop)
add 1
           ;(implicit jnz) set exit marker (end of loop, jump if not zero)

Brachylog, 6 bytes


Try it online!


#>         Constrain a number in [1,∞)
  =        Assign a value to the number in that interval
   @w      Write the number followed by a linebreak
     \     False ; try another value assignement in the interval

Alice, 6 bytes

h .\

Try it online!

Alice is a 2D language with two modes - Cardinal (up/down/left/right) for integers and Ordinal (diagonal) for strings. For this challenge we need Cardinal to count and Ordinal to print as an integer (as opposed to a byte).

We start off from the top left in Cardinal mode, with h incrementing the top of stack — for the first iteration, this is an implicit 0. The space that follows is a no-op, and the . after duplicates the top of stack.

Next we pass through the mirror \, reflecting us NE and switching us to Alice's Ordinal mode. In Ordinal mode the IP reflects off the code boundary rather than wrapping around, so we rebound and start moving SW.

From here we bounce twice, hit the O to print as integer, and bounce back to the \. This switches us back to Cardinal mode moving rightward, wrapping around and continuing the infinite loop.


0123  ->  h5.3  ->  h7 9  ->  01.9  ->  ...
O         6 4       6 8       O

ArnoldC, 157 bytes


First time trying to use ArnoldC so any improvements are welcome. I ran it here and it seemed to work even though the output stops around 1700. I believe this is a limitation of that test though, not the code.


cQuents, 1 byte


Try it online!


:    Implicit mode : (infinitely print the sequence if given no input)
 $   Each item in the sequence equals the current (1-based) index

Brainfuck, 1055 bytes


Too bad that Brainfuck has limited memory cell size. Actually, printing decimals and conditional statements are pain in this language. Ungolfed (or called so):





    INCREMENTING <<<<<<<<<-]>>>>>>>>>>>[<<<<<<<<<<<<+>>>>>>>>>>>>-]<<<<<<<<<<<<[>[-]+<-]>[<+>>>>>>>>>[-]>[<+<<<<<<<+>>>>>>>>-]<<<<<<<<[>>>>>>>>+<<<<<<<<-]>>>>>>>+>[-]<[>+<-]
    CHECKING CELL [-]>[<+<<<<<<<+>>>>>>>>-]<<<<<<<<[>>>>>>>>+<<<<<<<<-]>>>>>>>>>[-]<<[<<<<<<+>>>>>>-]->>[<<<<<<<<-<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>[>>>>>>+<<<<<<[-]]<->>>>>>>[<<<<<<<->>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>[>>>>+<<<<<<<<<<<<<->>>>>>>>>[-]]<<<<<<<<-]<[>[-]+<-]>[<+>>>>>>>>>>>>>>+<<<<<<<<<<<<<<->-]>>>>>>>>>>>>  [<<<<<<<<<<<<<+>>>>>>>>>>>>>-]


                PRINT INTEGER


                PRINT SPACE





If we would remove last piece of code it would stick two '1' at the end.

  • 1
    \$\begingroup\$ Welcome to PPCG! There is already a brainfuck answer here, but multiple answers in the same language are perfectly fine here. Nice answer! \$\endgroup\$ Oct 24 '17 at 15:54
  • \$\begingroup\$ "Printing decimals and conditional statements are a pain in this language." Everything is a pain in brainfuck. That's sort of the point. \$\endgroup\$
    – KSmarts
    Nov 17 '17 at 15:15
  • \$\begingroup\$ @KSmarts Not really, some things are ridicously easy \$\endgroup\$ Nov 17 '17 at 19:17

Retina, 13 bytes


Try it online!


Retina 1.0 has a new feature which lets us solve this with an algorithm that conceptually uses a unary representation of the number, but still won't run out of memory. You can test this by initialising the string to a really high number, in that case the program will count from there.

So incrementing decimal numbers isn't really something Retina does, because it only works with strings. Leaky Nun has shown a way to increment decimals, but it's comparably complicated.

What Retina can do with decimal integers is a) repeat a character or string n times and b) measure the length of a string. So the idea is to take the last integer n, generate a string with n+1 characters, and measure its length, and use this as our new result. That's what the code does:

  • ^.* match the current string. We need to use .* instead of .+ because the string is initially empty (the program's input), and ^ because .* would otherwise yield two matches on subsequent iterations.
  • We substitute the match with $.(*__. There is some implicit syntax going on here. The ) is closed implicitly and * has an implicit left-hand operand of $&, so this substitution is really short for $.($&*__). $&*_ generates the string of n underscores (when $& is empty, i.e. on the first iteration, it is treated as zero). The second _ appends another underscore to that, generating a string of n+1 characters. $.(…) measures the length of that string, so we end up with the next integer.
  • \ tells Retina to print the result of this substitution with a trailing linefeed.
  • + runs the entire thing in an infinite loop (+-loops can terminate, but this one won't).

So why does this work for large integers without running out of memory? Retina's $.(…) computation is lazy! Whenever possible, its string argument isn't actually fully evaluated, but its length is computed directly instead. And it knows that a string formed with n*s is n*len(s) characters long. This feature gives us the convenience of a unary approach without the memory requirements. The length computation also uses an arbitrary-precision integer type, so that we can go well beyond 2128.


Chip, 2214 bytes

Noncompeting: this uses language features that post-date the challenge. For a competing entry that is too inefficient to run, see the edit history.

2211 bytes for the code, plus 3 bytes for the -w flag.

o z*
`K\' ,--K   ,--K   ,--K   ,--K   ,--K   ,--K   ,--K8  ,--K   ,--K   ,--K   ,--K   ,--K   ,--K   ,--K   ,--K
o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o
o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o
o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o
o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o
o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o
o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o
o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o
o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o | o#-o,' o#-o
 `---'  `---'  `---'  `---'  `---'  `---'  `---'  `---'  `---'  `---'  `---'  `---'  `---'  `---'  `--'
o-zo/a o-zo/a o-zo/a o-zo/a o-zo/a o-zo/a o-zo/a o-zo/a o-zo/a o-zo/a o-zo/a o-zo/a o-zo/a o-zo/a o-zo/a o-zo/a
oz-o/b oz-o/b oz-o/b oz-o/b oz-o/b oz-o/b oz-o/b oz-o/b oz-o/b oz-o/b oz-o/b oz-o/b oz-o/b oz-o/b oz-o/b oz-o/b
o-zo/c o-zo/c o-zo/c o-zo/c o-zo/c o-zo/c o-zo/c o-zo/c o-zo/c o-zo/c o-zo/c o-zo/c o-zo/c o-zo/c o-zo/c o-zo/c
oz-o/d oz-o/d oz-o/d oz-o/d oz-o/d oz-o/d oz-o/d oz-o/d oz-o/d oz-o/d oz-o/d oz-o/d oz-o/d oz-o/d oz-o/d oz-o/d
o-zo/e o-zo/e o-zo/e o-zo/e o-zo/e o-zo/e o-zo/e o-zo/e o-zo/e o-zo/e o-zo/e o-zo/e o-zo/e o-zo/e o-zo/e o-zo/e
oz-o/f oz-o/f oz-o/f oz-o/f oz-o/f oz-o/f oz-o/f oz-o/f oz-o/f oz-o/f oz-o/f oz-o/f oz-o/f oz-o/f oz-o/f oz-o/f
o-zo/g o-zo/g o-zo/g o-zo/g o-zo/g o-zo/g o-zo/g o-zo/g o-zo/g o-zo/g o-zo/g o-zo/g o-zo/g o-zo/g o-zo/g o-zo/g
oz-o/h oz-o/h oz-o/h oz-o/h oz-o/h oz-o/h oz-o/h oz-o/h oz-o/h oz-o/h oz-o/h oz-o/h oz-o/h oz-o/h oz-o/h oz-o/h

This solution gives output in 128 bits / 16 bytes, big endian. It has two main sections, one for incrementing, and the other for timing, storage, and output. There is likely a smaller implementation out there, but I haven't yet conceived of it.

Try it online for the 128-bit version.
Try it online for the 16-bit version, much faster than the 128 bit version.

Notes about the TIO: The -v flag is included, which shows the actual incoming/outgoing binary on stderr. In the TIO, we also provide a -cN flag, which cuts off the program after N bytes have been produced.


Chip is a (mostly) 2D language that operates on individual bits, which is why it needs a lot of space for 128-bit support. I won't get into the specific details (because we'd be here all day), but here's the gist of what's going on:

  • Layers:
    This is a layer divider. Lines above form the first layer, lines below form the second. Wherever there are o's on both layers, a connection is formed.
  • Incrementing:
     K   ,--
    o#-o |
    o#-o |
    o#-o |
    o#-o |
    o#-o |
    o#-o |
    o#-o |
    o#-o |
    Each # is a half-adder, and each column of # serves to increment the eight inputs on the left to the eight outputs on the right. The K at the top is a caching element to help with call stack efficiency. The tail is a wire to bring the carry back up to the next incrementor. There are sixteen such incrementors, for the sixteen bytes required to produce 128 bits. The 8 seen near the eighth incrementor is used for cache priming. This element is always the first element polled each cycle, and so it primes all caches to it's left. This prevents a stack overflow when we eventually compute the values to the right.
  • Storage:
    Each z reads a signal in on its top/right, and outputs that signal to the bottom/left. Therefore, these columns act as registers to hold the current state for the next cycle to use. The z's are offset from each other to prevent cross-talk. Again, sixteen such columns, one per byte.
  • Output:
    The letters a through h correspond to each of the bits of the byte that will be output, with a being the least signficant bit. The columns of /'s are switches that interact with the timing circuit to determine which byte is due to be output. Once more, sixteen columns, one per byte.
  • Timing:
    o z*
    The timing circuit consists of two parts. The portion on the first layer produces a high signal on the first clock tick only (to get it all started) and connects the rest of the timing circuit to the incrementors (increments by 1 only every 16th tick, increments by 0 otherwise). The portion on the second layer controls the actual sequencing. The pattern is to increment the value and output the highest byte, then output each successive byte without incrementing anything. When all bytes have been printed, the cycle repeats. (There is a cache element K and an or-gate ) that acts as a diode; these are again for efficiency only.)
3 4 5

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.