# Print all integers

Write a program or function which will provably print all integers exactly once given infinite time and memory.

Possible outputs could be:

0, 1, -1, 2, -2, 3, -3, 4, -4, …

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -2, -3, -4, -5, -6, -7, -8, -9, 10, 11, …


This is not a valid output, as this would never enumerate negative numbers:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …

• The output must be in decimal, unless your language does not support decimal integer (in that case use the natural representation of integers your language uses).

• Your program has to work up to the numbers with the biggest magnitude of the standard integer type of your language.

• Each integer must be separated from the next using any separator (a space, a comma, a linebreak, etc.) that is not a digit nor the negative sign of your language.

• The separator must not change at any point.

• The separator can consist of multiple characters, as long as none of them is a digit nor the negative sign (e.g. ,  is as valid as just ,).

• Any supported integer must eventually be printed after a finite amount of time.

### Scoring

This is , so the shortest answer in bytes wins

var QUESTION_ID=93441,OVERRIDE_USER=41723;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>

• If our language supports infinite lists, can we output the list from a function rather than printing? (Calling print on such a list would print its elements one at a time forever.) – xnor Sep 16 '16 at 8:57
• I feel like the requirement on arbitrary-size integers does nothing but discourage languages without such integers from participating. They either have to have an import they can use or solve a totally different challenge from everyone else. – xnor Sep 16 '16 at 9:10
• @xnor Changed, though that kinds of ruins the very name of the challenge. – Fatalize Sep 16 '16 at 9:14
• @xnor, languages with arbitrary precision integers still have to solve a different problem from everyone else, so all that that change has accomplished is to make this problem boringly trivial in a lot of languages. – Peter Taylor Sep 16 '16 at 9:54
• @PeterTaylor Yeah, this is unfortunate. The wrapping solutions don't feel to me like they are printing any negatives, but I don't see a way to firmly specify the difference when it's a matter of representation. – xnor Sep 16 '16 at 9:58

# Common Lisp, 42 bytes

(do((i 0))(())(print(- i))(print(incf i)))


Try it online!

# Implicit, 65 4 bytes on TIO

(%.ß


Requires that the input box on TIO be empty.

(...    « do..while top of stack truthy                 »;
%      «  print top of stack as int                    »;
.     «  increment (reads from input if stack empty)  »;
ß    «  print space                                  »;
¶   « (implicit) just kidding, loop forever         »;


Try it online!

# Implicit, 5 bytes

0(%.ß
0        « push 0           »;
(%.ß    « (same as above)  »;

• But how does this eventually print the negative numbers? – user85052 Dec 14 '19 at 6:48

# Momema, 26 bytes

z0-8*0-9 00+1*0-8-*0-9 0z1


Try it online!

This outputs null bytes as the separator (though TIO displays them as spaces).

Alternatively, at a cost of 1 byte, here's a version that uses tabs instead of null bytes:

z0-8*0-9 9 0+1*0-8-*0-9 9z1


## Explanation

                                                   #  a = 0
z   0     #  label z0: jump past label z0 (no-op)  #  while true {
-8  *0    #            output number [0]           #    print a
-9  0     #            output chr 0                #    print '\0'
0   +1*0  #            [0] = [0] + 1               #    a++
-8  -*0   #            output number -[0]          #    print -a
-9  0     #            output chr 0                #    print '\0'
z   1     #  label z1: jump past label z1          #  }


# Forked, 21 bytes

%A!v
>1+%A!AF*!%A!


First, this does %A! (print 0 followed by a newline), then executes the code in my original answer below, before I realized we were supposed to print 0 too:

# Forked, 12 bytes

1+%A!AF*!%A!


Try it online!

• 1+ - add 1 to the top of the stack
• % - print top of stack as integer
• A! - print 0xA (ASCII newline)
• AF*! - print 0xA × 0xF = 0x2D (ASCII -)
• % - print top of stack as integer
• A! - print 0xA (ASCII newline)

Forked is two-dimensional, so the IP wraps upon hitting the edge of the playing field.

This just loops through every integer, prints it followed by a newline, then prints it again, preceded by a - and proceeded by a newline.

# Appleseed, 41 bytes

(def I(q(((n 0))(cons n(I(sub(less? n 1)n


Defines a function I that takes no arguments and returns an infinite list of integers, starting (0 1 -1 2 -2 ...). Try it online!

Note: Appleseed is in the early stages of development at the moment, so if this code stops working at some point in the future, ping me and I'll update it.

### Ungolfed + explanation

; Load the library for functions & macros such as lambda
; Define all-integers to be...
(def all-integers
; a lambda function with one optional argument, n, whose default value is 0
(lambda ((n 0))
; The function prepends n to...
(cons n
; the result of a recursive call...
(all-integers
; whose argument is (n<1) - n, i.e. -n if n is positive, else -n+1
(sub (less? n 1) n)))))


# Pyt, 11 bytes

00Ƥ⁺ĐĐ~ƤƤł


Try it online!

00   pushes 0 twice
Ƥ    prints with a newline separator
    indicator for looping
⁺    increments
ĐĐ   duplicates twice
~    negates top value
ƤƤ   prints positive and negative value
ł    loops till top is zero (never)


# Coconut, 25 bytes

def f(n=0)=[n,~n]::f(n+1)


Try it online!

# Milky Way, 9 bytes

&{!k1-!j}


Try it online!

## How?

           initial Stack: ["", 0]
&{      }  infinite loop
!        output ToS
k       negative absolute value
1-     subtract 1
!    output ToS
j   absolute value


# QBasic, 23 bytes

Script that takes no input and outputs to the console. Values are newline delimited and increment in the order of $0, -1, 1, -2, 2, \cdots$.

?0
Do
i=i+1
?-i
?i
Loop


## Python 3, 44 bytes

i=0;print(i)
while 1:i+=1;print(i);print(-i)


Try it online!

# Keg, -pn, 15 9 bytes

0.1{:④±.⑨


Try it online!

### 15 bytes

0. ,1{④± ,④ ,±⑨


Try it online!

Really messy I know, but it works. Integers are space seperated

## Wd, 6 5 bytes

Newline-separated. Look ma, no bitwise magic!

▲h(2Z


## Explanation

Decompressed:

0      % Print 0 (the implicit not-given operand, to be precise)
i   E % In the range 1..infinity...
a    % Explicit loop variable
P   % Print the number with a newline
_  % Negate the number
% Implicit print on each iteration
% Make sure that the second-to-top executes (this is now implicit)


# cQuents, 7 bytes

=0:k,-k


Try it online!

Do you really need an explanation?

# LaTeX, 97 bytes

\def\f{\typeout0\newcount\n\n=1\loop\typeout{\the\n}\typeout{-\the\n}\advance\n1\ifnum1=1\repeat}


Defines a macro \f that writes to stdout.

## Explanation

\def\f{                % define a macro \f
\typeout0             % write a 0
\newcount\n           % define a new counter n
\n=1                  % set n to 1
\loop                 % this is like a do-while loop
\typeout{\the\n}     % write n
\typeout{-\the\n}    % write -n
\advance \n 1        % increment n by 1
\ifnum 1=1            % this is the loop condition, continue if 1=1
}


# Red, 37 bytes

n: 1 forever[print[n 0 - n]n: n + 1]0


# Turing Machine Code, 460 bytes

This prints the list in Unary so I'm hoping this still counts since, in Turing Machine Code, the concept of a 'number base' isn't built in. I'm going to mull over a base ten solution and post it separately if it exists and I find it.

0 * 1 r 2
2 * , r 3
3 * - r 4
4 * 1 r 5
5 * * r 5
5 _ , r 6
6 * * r 6
6 _ 1 * 7
7 * * l 7
7 , , l 8
8 * * l 8
8 - - r 9
9 1 @ r a
8 , , r g
g 1 @ r a
g - - r a
a * * r a
a _ 1 l b
b * * l b
b @ 1 r c
c 1 @ r a
c , , r d
d * * l d
d - - r 6
d , , r e
e * * r e
e _ , r f
f _ - r h
h * * l h
h , , l i
i * * l i
i , , r j
j 1 @ r k
j , , r m
k * * r k
m * * r m
m _ , r n
k _ 1 * o
o * * l o
o , , l p
p * * l p
p , , r q
p @ 1 r j
q * * r q
q _ , r n
n _ 1 r 7


Try it online!

# Symja, 38 37 bytes

i=0;While(0<1,Print(i);i++;Print(-i))


Try It Online!

To see that this will work for all integers, view this demonstration for numbers up to 100.

# Bash, with no external utilities, and no integer size limits, 210 bytes

echo 0
while
:
do
j=$i@ while k=${j/9@/@0}
[ $k !=$j ]
do
j=$k done j=${j/0@/1}
j=${j/1@/2} j=${j/2@/3}
j=${j/3@/4} j=${j/4@/5}
j=${j/5@/6} j=${j/6@/7}
j=${j/7@/8} j=${j/8@/9}
i=${j/@/1} echo$i
echo -$i done  Try it online! If you wish to see it run with large integers, initialize i to a large integer. # C, 55 Bytes i=1;f(){putc('0');while(i>0){printf(",%d,%d",-i,i++);}} ## Explanation /*int*/ i = 1; int f() { putc('0');/*Print out 0 because -0 isn't a number*/ while(i>0) /*i>0 handles overflow, ensuring all valid * * integers are printed once and only once */ { printf(",%d,%d",-i,i++); /* Unpacking the above line: the 1st %d prints out -i the 2nd %d prints out i i++ adds 1 to i(after it's passed to the printf)*/ } }  I put the comma at the beginning of the printf statement so that I didn't have to put it at the end of the puts and at the end of the printf. Output: 0,-1,1,-2,2... ## Edit: full C program version @cleblanc made an answer that is a full C program, rather than a function, so I decided to do that too(Our answers are otherwise completely separate). # C, 58 Bytes i=1;main(){putc('0');while(i>0){printf(",%d,%d",-i,i++);}} ## Explanation More or less the same as the original answer, but changing the function's name to main makes it a standalone program, rather than a function. # F# (.NET Core), 46 bytes My first F# golf. let rec c x= printf"%d,%d,"(1-x)x x+1|>c c 1  Try it online! ## MATLAB 65 bytes My earlier post was faulty because the loop does not stop. A better try is this: a=intmin('int64');(a:-a)'  but while this will work for the smaller int8 type it will not for int64 as the maximum array size will (of course) be exceeded. Note that transposing the vector prevents the console output from being interrupted by 'columns m to n' messages. Another funny with MATLAB is that integers do NOT roll over, thus intmax('int64') + 1 == intmax('int64') not intmin('int64') as I expected. Also, MATLAB does not have a 'do' loop, So the best I can think of is this: a=intmin('int64');b=-a;while(1) a, if a==b break, end; a=a+1; end  an then only if we allow the 'any separator' to allow this: a = -9223372036854775808 a = -9223372036854775807 ... a = 9223372036854775806 a = 9223372036854775807  There must be a better way! # C, 64 Bytes f(n){printf(",%d",n);n>0?f(-n),f(++n):0;}main(){f(printf("0"));}  A full program that terminates after printing all the integers it can represent. Output 0,1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7,8,-8,9,-9,10,...  # Oracle SQL 11.2, 777372 68 bytes SELECT CEIL((LEVEL-1)/2)*(MOD(LEVEL,2)*2-1)FROM DUAL CONNECT BY 1=1;  # Non-wrapping Brain****, 9 bytes Thanks to Scepheo for saving one byte! +[.+<.->]  • Duplicate answer. (the first part anyway) – Martin Ender Sep 16 '16 at 13:39 • Non-wrapping can be shorter by printing before decrementing: +[.+>.-<] – Scepheo Sep 16 '16 at 13:47 ## Bash, 33 55 bytes for((;;)){ echo -n$[-i++],$i,;((i==LLONG_MAX))&&exit;}  Unfortunately bash won't give an integer overflow error when $i exceeds the maximum size of the type used to store it. Therefore, I updated the code to include a termination criteria, that requires $LLONG_MAX to be defined in the environment or passed on the command line. Run example: on my system bash uses signed 64-bit integers LLONG_MAX=$[2**63-1] ./all_integers.sh


The following code is a 32 byte version (1 less) of my original post, that assumed undefined printing behavior after the integer overflow.

for((;;)){ echo -n $[-i++],$i,;}


# C, 51 50 bytes

void f(){long i=0;for(;;)printf("%d %d ",i++,-i);}


I could save a byte by doing int instead of long, but since this can go longer than int without wrapping I'm leaving it.

Output:

0 -1 1 -2 2 -3 3 -4 4 -5 5 -6 6 ...

• This program will run forever, shouldn't it terminate after printing all the "longs"? P.S. you can save a byte using for(;;) in place of while(1) – cleblanc Sep 16 '16 at 17:30
• A lot of the other answers here run forever, so I just went with it. That way, you can #define long into arbitrarily large types. Good tip on saving a byte though. – Cody Sep 16 '16 at 18:07
• It's pointless to use long with a %d conversion (instead of %ld). On x86-64 with 64-bit long, printf it will only look at the low 32 bits of its args. I can't think of a plausible way for any normal calling convention on any ISA where %d would print a number outside the range of int; most calling conventions require functions to ignore garbage in high bits. You could save a ; by putting the variable declaration inside the for(). i.e. for(int i=0;;)printf.... Especially since you didn't omit the return-type or anything, so this is valid C99. – Peter Cordes Sep 16 '17 at 7:35
• By the way, you can save 5 bytes by removing void . The function will be declared as int, which will give a warning, but this is code golf, not following best practices. – JustinCB May 6 at 14:56

# C++ with Boost, 143 bytes

#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>
boost::multiprecision::cpp_int i;main(){while(++i)std::cout<<1-i<<','<<i<<',';}


Not very short, but it does use an arbitrary-precision type. To test that, I tried replacing ++i with i=2*i+1, and very soon there were numbers several hundred digits long being printed correctly. This should work until the number takes up all your stack memory.

• Suggest turning the while loop into a for loop, replacing ',' with 44 and deleting the space after #include. – ceilingcat Nov 10 '16 at 1:38

(Int.min...Int.max).map{print($0)}  Really, we should be able to get this down to 30 bytes like so: (Int.min...Int.max).map(print)  But the compiler doesn't allow this yet. • 30 bytes: print(Array(Int.min...(.max))) – Tamás Sengel Mar 29 '18 at 20:55 # k (20 bytes) The function between curly braces is repeatedly iterated on it's result, starting at zero, until the result converges at 0W (k infinity). {-1@'$?-1 1*x;x+1}/0


The function prints the argument and its negation and then returns incremented argument.

# C# function 53 bytes

int j;void X(){for(;;)Console.Write(\$"{j++},-{j},");}


Explanation:

Create a variable "j" in class scope. This will default to have a value of zero. Write and increment value and then write the negative of that value. This will output "0,-1," on the first loop and "1,-2," on the 2nd loop.