# 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

# 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!

# GolfScript, 16 14 bytes

1{.p.1\-p).}do


# Explanation:

1              # Set counter to 1
{        .}do # While counter is nonzero:
.p           # Print counter
.1\-p      # Print counter - 1
)     # Increment counter by 1


Try it online!

# Wren, 50 bytes

var n=0
while(n)n=-System.print(1-System.print(n))


Try it online!

## Explanation

var n=0 // Set n as 0
while(n)                                   // While n is an integer:
System.print(n)  // Output n
System.print(1-               ) // Output 1-n
n=-                                // Set n as the number negated


# 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

# Runic Enchantments, 24 bytes

8?;>0$'$01+:$'$Z:$'$Z


Try it online!

' $ is just as long as any other way of printing a character (such as ak$) so with a required separator, that's as short as it gets.

Will print forever until the value exceeds the binary representation and sign-overflows (which is acceptable for questions with an infinite memory assumption), whereupon it will repeat.

# Python 2, 32 bytes

i=0
while 1:print i;print~i;i+=1

• You could also do i=0 (newline) while 1:print i;print~i;i+=1 if you wanted – ETHproductions Dec 29 '16 at 18:16
• If you need rep for your chat bot account, consider making a meaningful contribution to the site. This adds absolutely nothing over the pre-existing 27 byte Python answer. – Dennis Dec 29 '16 at 22:34

# x86-16, IBM PC DOS, 47 bytes

### Binary:

00000000: 33c9 bd0a 0050 0bc0 7d09 50b8 2d0e cd10  3....P..}.P.-...
00000010: 58f7 d833 d2f7 f552 410b c075 f658 b40e  X..3...RA..u.X..
00000020: 0c30 cd10 e2f7 b020 cd10 5840 75d7 c3    .0..... ..X@u..


Build and test using xxd -r

### Unassembled listing:

33 C9       XOR  CX, CX         ; clear counter
B3 0A       MOV  BL, 10         ; BX is divisor
INT_LOOP:
50          PUSH AX             ; save registers
0B C0       OR   AX, AX         ; is AX negative?
7D 09       JGE  DIGIT_LOOP     ; if positive, start digit loop
50          PUSH AX             ; save number
B8 0E2D     MOV  AX, 0E2DH      ; BIOS tty function, '-' char output
CD 10       INT  10H            ; write to console
58          POP  AX             ; restore AX
F7 D8       NEG  AX             ; AX = -AX
DIGIT_LOOP:
33 D2       XOR  DX, DX         ; clear high word of dividend
F7 F3       DIV  BX             ; AX = quotient, DX = remainder
52          PUSH DX             ; save remainder on stack
41          INC  CX             ; increment counter
0B C0       OR   AX, AX         ; quotient = 0?
75 F6       JNE  DIGIT_LOOP     ; no, keep going
PRINT_LOOP:
58          POP  AX             ; restore digit in AL
B4 0E       MOV  AH, 0EH        ; BIOS tty function
0C 30       OR   AL, '0'        ; convert to ASCII
CD 10       INT  10H            ; write to console
E2 F7       LOOP PRINT_LOOP     ; loop until all digits displayed
B0 20       MOV  AL, ' '        ; space char
CD 10       INT  10H            ; write to console
58          POP  AX             ; restore counter
40          INC  AX             ; increment to next number
75 D7       JNZ  INT_LOOP       ; loop until 0


(This program is basically just an itoa() function...)

### Output

A standalone DOS executable. Using default 16-bit integer size for 8088, writes all numbers in decimal to console.

Tail:

## 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 # 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 # Swift 3 (34 bytes) (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

## Actually, 7 bytes

01W;±@u


This solution requires infinite time to actually print anything. Finite memory will cause an out of memory error and premature printing. No TIO link for obvious reasons.

Explanation:

01W;±@u
0        push 0
1       push 1
W      infinite loop:
;       duplicate
±      unary negate
@     swap with positive
u    increment


This solution works for 8 bytes, prints a finite amount of numbers in a finite amount of time, and uses significantly less memory (the memory used doesn't start growing until after INT_MAX is printed, at which point Python seamlessly transitions to arbitrary-precision integers).

0■~W■±■~


Try it online! (only prints up to around 9292 due to timeout).

Explanation:

0■~W■±■~
0         push 0
■        print entire stack without popping (just the 0)
~       bitwise negate (~n is equivalent to -n-1)
W      infinite loop:
■       print stack without popping
±      unary negate
■     print without pop
~    bitwise negate

• This solution requires infinite time to actually print anything contradicts Any supported integer must eventually be printed after a finite amount of time – Fatalize Sep 17 '16 at 13:01
• @Fatalize Integers will be printed after a finite amount of time, if there's a finite amount of memory available. – Mego Sep 17 '16 at 17:59
• and they will never get printed in a finite amount of time with an infinite amount of memory, so this answer is invalid – Fatalize Sep 17 '16 at 18:13
• @Fatalize Then please clarify that in the challenge body. – Mego Sep 17 '16 at 20:46

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

# Python, 40 bytes

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

• You need to remove the p(0) line, or else 0 will be printed 3 times. – Mego Sep 26 '16 at 6:40

C++, 84 Bytes

#include <iostream>
int main(){for(int i=0;;)std::cout<<i++<<','<<-i<<',';return 0;}


Edit: thanks for the debugging, commenters

• Welcome to PPCG! All answers need to be full programs or functions and the relevant includes/namespaces need to be counted as well. If you make your submission a full program, it should compile in any existing compiler as is, and if it's a function it should be possible to drop it into any program and use and compile it without any other additional code. – Martin Ender Sep 17 '16 at 15:53
• That loop doesn't print a delimiter between the numbers. – celtschk Oct 13 '16 at 23:08

## QBIC, 14 bytes

{?1-q ?q q=q+1


qis 1 by default in QBIC, so this prints (1-1=) 0, 1, -1, 2, -2... separated by line breaks.

## Straw, 26 bytes

~(~$:>(,-)>:>(,)>#0+~:&):&  Try it online! ~(~$:>(,-)>:>(,)>#0+~:&):&
~ ~                 ~      Swap between the two stacks
(                     )   Push a string literal
\$                       Unary -> decimal
:      :         :     Duplicate
>    > >   >          Output
(,-)   (,)           String literal
#         Decimal -> unary
0        Push the character '0'
+       Concatenate
&  & Evaluate


It prints -0 too, not sure if it's allowed though

# Pushy, 7 bytes

0[~#|h#


Try it online! (will eventually cut the output)

Explanation:

0     \ Push 0 as the starting counter
[     \ Infinitely:
~#   \   Negate counter (and print)
|h   \   Push abs(counter)+1
#    \   Print counter


This prints in the pattern 0 1 -1 2 -2 3 -3..., separated by newlines.

Pushy's reference implementation is in Python, which uses arbitrarily sized integers, and so there won't be any overflow if you run this for a long time. However, the integer would eventually get too large and cause a MemoryError.

# CJam, 10 bytes

0{_n~_nz}h


Try it online!

# Triangular, 21 bytes

()ip.%@,|<.>A@\/A|%p<


(Does not work on the TIO version yet.) Formats into this triangle:

     (
) i
p . %
@ , | <
. > A @ \
/ A | % p <


This got really messy once I realized there had to be delimiters between the numbers.

The directionals (<,>\/) poke the IP around to get this code executed:

(i%|A@p%|A@p)


How it works:

• ( opens a loop.
• i increments the top of stack.
• % prints the top of stack as an integer.
• | negates the top of stack.
• A pushes 10 to the stack.
• @ prints the top of stack as ASCII \n.
• p pops the 10. Now the top of stack is the negated value.
• % prints the top of stack (negated value).
• | un-negates the top of stack.
• A pushes 10 to the stack again.
• @ prints as ASCII \n.
• p pops the top of stack.
• ) unconditionally jumps back to the loop.

# Aceto, 9 bytes

dpnd~pnIO

d duplicates the top val
p prints it
n does a newline
~ negates  the top val
I Increments the top val
O returns to the beginning of the program

Try it online!

# uBASIC, 24 bytes

An anonymous answer that takes no input and outputs to the console.

0?0
1i=i+1:?i,0-i:GoTo1:


Try it online! (and yes, the terminal : is necessary)

# MY-BASIC, 38 bytes

Print 0;
While 1
i=i+1
Print-i;i;
Wend


Try it online!