70
\$\begingroup\$

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

Rules:

  • 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.

Catalogue

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>

\$\endgroup\$
  • 29
    \$\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
  • 6
    \$\begingroup\$ For future challenges, may I recommend the sandbox such that all these details could be sorted out before people start posting answers? :) \$\endgroup\$ – Martin Ender 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\$ – Paŭlo Ebermann 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\$ – gregsdennis Nov 15 '15 at 20:45

182 Answers 182

2
\$\begingroup\$

c + GMP library, 90

Score includes +4 for passing -lgmp to the compiler. You'll need GMP installed to build and run this.

Here's how we do arbitrary precision in c:

#include<gmp.h>
main(){mpz_t i;for(mpz_init(i);mpz_add_ui(i,i,1),gmp_printf("%Zd\n",i););}

Compile with:

cc forever.c -o forever -lgmp
\$\endgroup\$
  • \$\begingroup\$ I don't understand... what's wrong with double long unsigned long i; for(i=0;1>0;i++){printf("v%\n",i)} ? \$\endgroup\$ – cat Dec 29 '15 at 16:04
  • \$\begingroup\$ @cat I'm not familiar with the double long unsigned long type - which compiler are you using? GCC doesn't like it. \$\endgroup\$ – Digital Trauma Dec 29 '15 at 16:55
  • \$\begingroup\$ GCC compiled it for me but I didn't realise it segfaulted, never mind ¯_(ツ)_/¯ \$\endgroup\$ – cat Dec 29 '15 at 17:04
  • \$\begingroup\$ You can remove first include and replace stdout with 1. \$\endgroup\$ – Krzysztof Szewczyk Feb 13 '18 at 17:37
  • \$\begingroup\$ @KrzysztofSzewczyk How would that work? stdout the stream associated with the STDOUT fd (commonly numerical 1), but is itself a FILE * pointer. mpz_out_str() needs a FILE * and not an int 1. \$\endgroup\$ – Digital Trauma Feb 13 '18 at 19:15
2
\$\begingroup\$

Brachylog, 4 bytes

ℕ₁ẉᶠ

Explanation

ℕ₁      --  Get a integer which is at least 1
  ẉᶠ    --      and print all possible values (ordered from 1 to inf)

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Deoxyribose, 35 29 bytes

ATGCCAGAAAAACATAACGGTTTAAATCC

Explanation:

ATG
CCA     (*) Divide (null/null yields 1)
  GAA     Dupe
  AAA     Pop
  CAT     Push
    AAC     1
  GGT     Move 
  TTA     Plus
AAT     Loop
  CC      *

I feel like this can get shorter.

Edit: Saved 6 bytes by making creative use of division of two empty stacks.

\$\endgroup\$
1
\$\begingroup\$

PHP, 31 bytes

<?for(;;)echo$i=bcadd($i,1),~õ;

I assume default settings, as they are without an .ini (you may disable your local .ini with the -n option).


Sample Usage

$ php -n countup.php
\$\endgroup\$
  • \$\begingroup\$ You can save 2 bytes by saying they should run it using php -r '...', \$\endgroup\$ – Kenney Nov 15 '15 at 2:24
  • \$\begingroup\$ @Kenney r'' should cost three. It also seems to violate the constraint, "Your program must be a full, runnable program, and not a function or snippet." \$\endgroup\$ – primo Nov 15 '15 at 8:07
  • 1
    \$\begingroup\$ As far as I am concerned, <? is at the templating level, and your code only really starts at for. It doesn't really say how the program is to be fed into the interpreter. But you're probably right! \$\endgroup\$ – Kenney Nov 15 '15 at 15:50
  • \$\begingroup\$ @Kenney the problem with that interpretation, is solutions that have anything outside the code tags, and also the use of <?=, e.g. codegolf.stackexchange.com/a/12569 \$\endgroup\$ – primo Nov 16 '15 at 0:53
  • 1
    \$\begingroup\$ @DougMcLean bcadd is necessary, because when the value exceeds PHP_MAX_INT, or the exactly representable floating point range (2^56), whichever comes first, it would fail to display an integer. \$\endgroup\$ – primo Nov 18 '15 at 2:29
1
\$\begingroup\$

Julia, 35 bytes

i=big(0);while 1>0 println(i+=1)end

This uses Julia's GMP-based arbitrary precision integers.

\$\endgroup\$
1
\$\begingroup\$

C++, 104 bytes

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

A translation of my C answer. This uses a terse range-based for loop, which is a C++1z feature briefly added to some compilers but later voted out of C++17. clang++ 3.5.2 compiles my code fine, but I'm not sure if it counts as "C++". I can change it to for(int b:c) if it's deemed invalid.

\$\endgroup\$
1
\$\begingroup\$

Go, 104 99 95 bytes

package main
import."math/big"
func main(){a:=&Int{}
for{println(a.Add(a,NewInt(1)).String())}}

Not terribly golfed yet, I might take the time to refine it later.

Note that this will not run on the playground since it runs forever.

\$\endgroup\$
1
\$\begingroup\$

VB.NET, 113 99 bytes

Well, pretty straightforward for .NET Framework 4. Needs a reference to System.Numeric.dll:

Module m
Sub Main
Dim i As Numerics.BigInteger
do
i+=1
Console.WriteLine(i)
loop
end sub
End Module

Not exactly original, but hey, even not that much longer than the C# answer ;-)

Thanks Berend for making me dig a little deeper into the compilation process, saving 14 bytes in the process.

\$\endgroup\$
  • \$\begingroup\$ You can remove System. (twice), for an extra 14 bytes. \$\endgroup\$ – Berend Nov 16 '15 at 10:28
  • \$\begingroup\$ @Berend No I can't. It may work when compiled in Visual Studio due to automatic namespace imports, but I consider that cheating ;-) Here I would need to add Imports System to the code, which adds the 14 bytes right back in \$\endgroup\$ – Jens Nov 16 '15 at 12:51
  • \$\begingroup\$ How do you compile then? Both Visual Studio (2013) and MSBuild don't care about the missing system. \$\endgroup\$ – Berend Nov 16 '15 at 12:59
  • \$\begingroup\$ I plug the code above directly into the codedom compiler. Figured it is the most "raw" form of compiling vb.net. Sounds like a meta discussion in all honesty :) \$\endgroup\$ – Jens Nov 16 '15 at 13:05
  • 1
    \$\begingroup\$ Maybe a silly question, but as requirements are at least 2^128 ; does BigInteger really required ? if not, you could gain an extra 22 bytes by declaring i with Dim i# (using double identifier type character) \$\endgroup\$ – Sehnsucht Nov 18 '15 at 2:49
1
\$\begingroup\$

Python 2, 24 bytes

Same method as the Python 3 answer.

i=1
while 1:print i;i+=1
\$\endgroup\$
1
\$\begingroup\$

JacobFck, 10 Bytes

This is so short!

^1:m^1+>_m

See expanded and commented here.

\$\endgroup\$
  • \$\begingroup\$ Does this work up to 2^128? \$\endgroup\$ – Dennis Dec 29 '15 at 20:43
1
\$\begingroup\$

Mouse-2002, 17 bytes

aa:(a.!"!"a.b+a:)

It seems there's a flaw in the interpreter which messes up using the stack for while loops, I dunno, so we use a variable instead.

\$\endgroup\$
1
\$\begingroup\$

Forth, 67 71 bytes

Forth doesn't have a builtin word for exponentiation, so we need to define one, because loops in Forth, which are frowned upon, need clearly defined bounds.

According to the language's original spec, this will segfault or run out of memory when it gets to 32,767 but that's not the case for mighty gforth! Instead, this runs out of memory whenever it's unable to continue storing numbers, as the stack's allocation is not dynamic like the heap's is, and do's operands (the limit and index) are put on the heap, not the stack, else they would interfere with the stack.

Essentially, it will stop at the same point every other answer here will.

The loop construct normally looks like 10 0 do ... loop where 10 is the limit and 0 is the index, i.e starting point.

In this example, we need to add one to the upper bound before counting there.

Edit: apparently do is a "compile-only" word, and it can only be found inside macro definitions.

: p over swap 1 ?do over * loop nip ;
: c 2 128 p 1 + 0 do i . loop ;
c
\$\endgroup\$
1
\$\begingroup\$

Matlab, 95 bytes

   for n=1:128;sym(sym(2^n)-1),for i=1:n sym(2^n+sym(sum(power(2,nchoosek(1:n,i)-1),2)-1)),end,end

  • This program can count over 2^128 just try with these parameters if you have doubts.

    for n=200:200;sym(sym(2^n)-1),for i=1:n sym(2^n+sym(sum(power(2,nchoosek(1:n,i)-1),2)-1)),end,end
    
  • This can be golfed more if I could figure out a way to combine two loops in one single executive loop, thats because the code skips one integer per 2^k the case of one loop.

\$\endgroup\$
1
\$\begingroup\$

Y, 9 bytes

0C:' gghX

Simple three-link program. 0C initializes the stack with a 0 and moves to the next link, : duplicates the current value ' pushes a space for a separator, gg prints twice, and h increments it. X is an unconditional wrap-around, so we go to the beginning of the link. Try it here!

\$\endgroup\$
1
\$\begingroup\$

D, 56 57 bytes

import std.stdio;void main(){for(real i;;writeln(i++)){}}

Pretty straightforward. D != Python.

The shortest while-loop version I can think of is longer, at 59 bytes:

import std.stdio;void main(){real i;while(++i){writeln(i);}}
\$\endgroup\$
1
\$\begingroup\$

ForceLang, 35 bytes

label l
io.writeln set a 1+a
goto l

ForceLang uses BigRationals as the default number type.

Also, in the latest revision, 1+nil yields 1, which is what allows this version to work (previously it would have yielded the string "1<nil>".)

nil+1, however, still triggers a null pointer exception.

\$\endgroup\$
1
\$\begingroup\$

UberGenes, 33 30 bytes

I'm giving two versions here, just to demonstrate the lang. Integers and memory in UberGenes are bounded only by computer memory, so both versions meet the "forever" requirement. This first one is for score:

=ii+a1=pa=q5=bi-p1=oQ:bp=oI=i0

It prints numbers in unary separated by '=' characters. Explanation (indents indicate a loop start):

=ii                                  NOP
   +a1                               INC a (initially 0)
   =pa                               COPY a INTO p
   =q5                               SET q=5 so it points to '1'
   =bi                               SET b to this location (15)
      -p1                            DEC p
      =oQ                            OUTPUT '1'
      :bp                            JUMP to b's location while p>0
   =oI                               OUTPUT the contents of this location ('=')
   =i0                               JUMP to the beginning of main loop.

The second version is more interesting (66 bytes):

=ii+a1=l0-l2=pa=z8*z6=t5*t2=bi=qp%qt+qz=Lq-l1/pt:bp=bi=oL+l1:bL=i0

It prints the numbers in decimal separated by NULLs.

How it works (indents indicate a loop start):

=ii                                  NOP
   +a1                               INC a (initially 0)
   =l0-l2                            SET l=-2
   =pa                               COPY a INTO p
   =z8*z6                            SET z=48 ('0')
   =t5*t2                            SET t=10
   =bi                               SET b to this location (27)
      =qp                            COPY p INTO q
      %qt                            MOD q BY 10
      +qz                            ADD 48 to q (turn it into character)
      =Lq                            PUT q AT MEM[l]
      -l1                            DEC l
      /pt                            DIVIDE p by 10
      :bp                            JUMP back to b's location if p>0
   =bi                               SET b to this location (51)
      =oL                            OUTPUT the character in MEM[l]
      +l1                            INC l
      :bL                            JUMP back to b's location if MEM[l]>0
   =i0                               JUMP back to beginning of main loop
\$\endgroup\$
1
\$\begingroup\$

Molecule, 7 bytes (6 chars)

0(1+~)

Explanation:

0(1+~)
0      add 0 to stack
 (     begin while statement
  1+   add one
    ~  print
     ) goto the beginning of while statement.
\$\endgroup\$
1
\$\begingroup\$

AutoHotKey, 34 bytes

Golfed and Ungolfed is the same.

Golfed:

c:=0
Loop {
    c:=c+1
    tooltip %c%
}

Ungolfed:

c:=0
Loop {
    c:=c+1
    tooltip %c%
}
\$\endgroup\$
  • \$\begingroup\$ not that it's a problem, but if golfed and ungolfed are the same why would you bother with both of them \$\endgroup\$ – undergroundmonorail Apr 25 '16 at 15:12
  • \$\begingroup\$ also does ahk really enforce indentation like that? it's been a long time since i used it, i don't remember \$\endgroup\$ – undergroundmonorail Apr 25 '16 at 15:13
  • \$\begingroup\$ It does, and the golfed and unfolded are just a universal format I use (I save each of my entries). \$\endgroup\$ – Michelfrancis Bustillos Apr 25 '16 at 17:05
1
\$\begingroup\$

Node.js + Big.js, 63 bytes

Use npm install big.js before running.

c=new require("big.js")(0);while(1)console.log(c+""),c=c.add(1)

Simple enough, and has arbitrary precision. Each number is seperated by newlines.

\$\endgroup\$
1
\$\begingroup\$

Tellurium, 6 bytes

[i|+^]

Pretty simple.

The program adds one to the selected cell (+), and then outputs it (^). Using i as a loop's value makes it run the code forever.

\$\endgroup\$
  • \$\begingroup\$ Does tellurium have arbitrary length integers? \$\endgroup\$ – vrwim May 20 '16 at 14:13
  • \$\begingroup\$ @vrwim I'm not sure, I think it counts up to Python's maxint, which is 2147483647. \$\endgroup\$ – m654 May 20 '16 at 15:33
1
\$\begingroup\$

Lua, 27 Bytes

i=1::a::i=i+1print(i)goto a
\$\endgroup\$
1
\$\begingroup\$

Befunge - 4 bytes

I’m surprised there isn’t already a Befunge answer on here.

1+:.
\$\endgroup\$
1
\$\begingroup\$

Perl 6, 13 bytes

.say for 0..*

Perl 6 has lazy/infinite arrays, so I'm abusing that to create an infinite range. This will never run out of memory.

Note: as explained in the Perl 6 docs, (0..*)>>.say would print out of order.

\$\endgroup\$
1
\$\begingroup\$

Pyke, 5 3 bytes

ohr

Try it here!

\$\endgroup\$
1
\$\begingroup\$

SmileBASIC, 87 bytes

S$="0"*#Y@L
I S$,127?S$GOTO@L
DEF I S,P
IF"0"<S[P]THEN S[P]="0"I S,P-1 ELSE S[P]="1
END

Uses a recursive function to increment a binary string.

\$\endgroup\$
1
\$\begingroup\$

Swift - 32 bytes

for i in 0...Int64.max{print(i)}

Swift - 33 bytes

var i=0;while true{print(i);i+=1}

Cannot provide a testing link, because on the online environments this produces a buffer overflow. However, you can test it in Xcode / Swift Playgrounds or if you have an apple computer, you can run it in the Terminal, after typing the 'swift' command and pasting the code in.

\$\endgroup\$
  • \$\begingroup\$ Since I haven't been able to reach you anywhere else: Please don't approve edits that golf code, such as this one. Site policy is to not do that. Please reject via "conflicts with author's intent" or "causes harm". \$\endgroup\$ – Rɪᴋᴇʀ Apr 24 '17 at 21:33
1
\$\begingroup\$

Billiards, 15 bytes/11 characters, non-competing

Non-competing, because the language was made after the challenge.

Inspired by PhiNotPi's Challenge

1/\
 ↥↑
\^/

Explanation: 1 summons a ball with value 1. It falls onto the \, which deflects it into the ^.

Then, it levitates from the ^, goes to the which prints its value. Then it deflects off the /, and then hits the \ and begins falling again. It hits the which increments its value, and then hits the / and deflects back into the ^.

Bonus: Replace 1 with a to output the starting point.

Bonus: Add b to the end of the first row and < to the end of the last row to specify the ending point.

\$\endgroup\$
1
\$\begingroup\$

APL (Dyalog APL), 13 14 10 bytes

{1+⎕←⍵}⍣≡0

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Braingolf, 10 bytes

1[!_2+# @]

Try it online!

\$\endgroup\$

protected by Community Mar 3 at 1:44

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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