# 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

## MATLAB 64 bytes

As a start, with nothing clever:

fprintf('0');a=int64(1);while(1) fprintf(' %d',[a -a]);a=a+1;end


Enter at the console, generates 0 1 -1 2 -2...

There must be a better way than this! Come on, folks...

• Why int64? The octave answer might give you some "inspiration" 😊 – Stewie Griffin Sep 16 '16 at 16:39
• I wrote this quite fast, so it can most likely be golfed a lot more, but this is a lot shorter: x=0;while 1;disp(x);x=x+1;disp(-x);end. It's 26 bytes shorter =) – Stewie Griffin Sep 22 '16 at 12:05
• I know this is old, but what Stewie's saying is that the default int in MATLAB is int32, whereas the default double goes up to 2^53 – Sanchises Nov 8 '16 at 22:03

# Reticular, 12 bytes

0dp1+dpd0#2j


Try it online!

## Explanation

0dp1+dpd0#2j   ; stack
0              ; [0]
dp            ; [0]   PRINTED 0
1+          ; [1]
dp        ; [1]   PRINTED 1
d0#     ; [1, -1]
2j   ; skip two spaces after the j, wrapping to..
p            ; [1]   PRINTED -1
1+          ; [2]
dp        ; [2]   PRINTED 2
d0#     ; [2]   PRINTED -2
; etc.


## Pyth , 7 bytes

0.V1_bb

Explanation

0       # print 0
.V1    # increment 'b' forever, starting on 1
_b  # print -b
b # print b


# Perl 6, 22 bytes

loop {say $--;say ++$}


## Explanation:

loop {
say   (state $= 0)--; # prints ｢0␤｣ first time around, then ｢-1␤｣ ｢-2␤｣ etc say ++(state$ = 0)    # prints ｢1␤｣ first time around, then ｢2␤｣ ｢3␤｣ etc
}


# bash, 46 Bytes

echo 0;for((i=1;;i++)){ echo -e "$i\n-$i"; }

• You don't need a space after ;, or after {. – Peter Cordes Sep 16 '17 at 7:37

### Brainfuck, 10 bytes

.+[>-.<.+]


Does not rely on cell wrapping to print the negative values. Does rely on accepting the cell value, which is commonly printed as a character by converting it to ASCII, to be the value to print.

Try it online!

# C 331 bytes

Note that this outperforms the long version as it really can do as many as memory will permit. It seems like it is bounded by strings of length max(size_t) which is true, but also definitionally the maximum memory that c will let us grab. Unfortunately it is very slow since it thrashes memory.

#include<stdlib.h>
int main(_,a,b,c,d,e)char*a,*b;size_t c,d,e;{return(_==1?printf("0\n"),main(2,0,0,1,0,0):_==2?main(3,"",0,c,0,0),main(2,0,0,c+1,0,0):_==3?(c?d=strlen(a),b=malloc(d),memcpy(b,a,d),b[d+1]=0,main(4,b,0,d,c-1,9),free(b),0:(*a-48?printf("%s\n-%s\n",a,a):0)):(e+1?a[c]=e+48,main(3,a,0,d,0,0),main(4,a,0,c,d,e-1):0));}


Prints 0, then 9,8,7,... then 99,98,97... etcetera. Can save 3 characters if we assume we don't care about output buffering (swapping \n for a space).

Process:

## Initial

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// prints base 0...0, base 0...1, etc with remaining digits after it.
void print_digit_permutations(char *base, size_t remaining)
{
int i;
char *newbase = malloc(strlen(base)+1);

if (!remaining) {
if (*base != '0')
printf("%s\n-%s\n",base,base);
return;
}

for (i = 0; base[i]; ++i) {
newbase[i] = base[i];
}
newbase[strlen(base)+1] = 0;

for (i = 0; i < 10; ++i) {
newbase[strlen(base)] = i + '0';
print_digit_permutations(newbase, remaining-1);
}

free(newbase);
}

int main()
{
char *base = "";
size_t i = 0;

printf("0\n");

for (;;) {
print_digit_permutations(base, ++i);
}

return 0;
}


## Unrolled

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void base_copy(char *newbase, char *base)
{
if (*base) {
*newbase = *base;
base_copy(newbase+1,base+1);
}
}

void print_digit_permutations(char*,size_t);
void print_all_digits(char *newbase, size_t baselen, size_t remaining, size_t count)
{
if (count+1) {
newbase[baselen] = count + '0';
print_digit_permutations(newbase,remaining);
print_all_digits(newbase,baselen,remaining,count-1);
}
}

void print_digit_permutations(char *base, size_t remaining)
{
int i;
char *newbase = malloc(strlen(base)+1);

if (!remaining) {
if (*base != '0')
printf("%s\n-%s\n",base,base);
return;
}

base_copy(newbase,base);
newbase[strlen(base)+1] = 0;

print_all_digits(newbase,strlen(base),remaining-1,9);

free(newbase);
}

void all(size_t size)
{
print_digit_permutations("",size);
all(size+1);
}

int main()
{
printf("0\n");
all(1);

return 0;
}


## Flat

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int print_digit_permutations(char *base, char *newbase, size_t remaining, size_t baselen, size_t _);
int print_all_digits(char *newbase, char *_, size_t baselen, size_t remaining, size_t count)
{
return (count+1?
newbase[baselen] = count + '0',
print_digit_permutations(newbase,newbase,remaining,0,0),
print_all_digits(newbase,newbase,baselen,remaining,count-1)
:
0);
}

int print_digit_permutations(char *base, char *newbase, size_t remaining, size_t baselen, size_t _)
{
return (remaining?
baselen=strlen(base),
newbase = malloc(baselen),
memcpy(newbase,base,baselen),
newbase[baselen+1] = 0,
print_all_digits(newbase,newbase,baselen,remaining-1,9),
free(newbase),
0
:
(*base-'0'?printf("%s\n-%s\n",base,base):0));
}

int all(char *_, char *_2, size_t size, size_t _3, size_t _4)
{
return print_digit_permutations("","",size,0,0),
all(_,_2,size+1,_3,_4);
}

int main()
{
return printf("0\n"),all("","",1,0,0);
}


## Main

#include <stdlib.h>
/* _ values:
*
* 1 - main
* 2 - all
* 3 - print_digit_permutations
* 4 - print_all_digits
*/
int main(_,a,b,c,d,e)char*a,*b;size_t c,d,e;{
switch (_) {
case 1:
return printf("0\n"),main(2,0,0,1,0,0);
case 2:
return main(3,"",0,c,0,0),main(2,0,0,c+1,0,0);
case 3:
return (c?
d=strlen(a),
b=malloc(d),
memcpy(b,a,d),
b[d+1]=0,
main(4,b,0,d,c-1,9),
free(b),
0
:
(*a-'0'?printf("%s\n-%s\n",a,a):0));
case 4:
return (e+1?
a[c]=e+'0',
main(3,a,0,d,0,0),
main(4,a,0,c,d,e-1)
:0);
}
}


And after removing whitespace and making a few other small changes we arrive at the initial golfed code. It is interesting that the 'proper' initial code is the second shortest at just over 700 bytes.

# Haxe, 46 bytes

function f(){var i=0;while(0<1)trace(i++,-i);}


## Racket 56 bytes

(saved 12 bytes with suggestion by @StevenH)

(λ()(let l((i 0))(printf"~a, ~a, "i(- -1 i))(l(+ 1 i))))


Ungolfed:

(define(f)
(let loop ((i 0))
(printf "~a, ~a, "  i  (- -1 i))


Following can also be used:

(for((i(in-naturals)))(printf"~a, ~a, "i(- -1 i)))


or:

(for ((i (in-naturals)))
(printf "~a, ~a, " i (- -1 i)))


Testing:

(f)

0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, -14, 14, -15, 15, -16, 16, -17, 17, -18, 18, -19, 19, -20, 20, -21, 21, -22, 22, -23, 23

• You can avoid the first printf entirely by replacing (* i -1) with (- -1 i). – Steven H. Oct 7 '16 at 6:17
• Thanks for the suggestion. I have added it to my answer. – rnso Oct 7 '16 at 6:29

# RProgN, 22 21 Bytes

►0p11¿]p]0\-p1+]}


Note the trailing space IS required.

Saved a byte by replacing the -1 * n with a simple 0 - n, because defining -1 in ► form takes too many bytes.

## Explination

►           # Read this word as a single-character based command.
0p          # Print the number 0
11          # Push two 1's to the stack.
¿           # While the top of the stack is truthy, pop the top of the stack.
]       # Clone the top of the stack, containing i.
p       # Print it.
]       # Clone it again.
0 \ - * # Push 0 to the stack, swap the 0 and the object underneith it, giving 0, n instead of n, 0. Subtract giving -n.
p       # Print it.
1+      # Add one to i
]       # Clone it for the next truthy check
}           # End the while statement
# Required to interpret the while loop correctly.


## Output

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


This language looks nothing like it's former self. ;(

# ForceLang, 8767 59 bytes

def w io.writeln
w 0
label a
w set i 1+i
w i.mult -1
goto a


# C, 44 bytes

long l;f(){printf("%ld ",l);l=(l<=0)-l;f();}


Note that the (implicit) int return type does not cause f to require a return because f never reaches the end of the function.

This code uses the fact that globally defined variables are initialized to zero.

Note that on a system with unlimited memory (or with a compiler that does tail recursion elimination)there will be no stack overflow, therefore this program fulfils the requirements.

# MATL, 9 bytes

0t_DQtDT


You can Try it online! (and let's hope that the process on the server actually terminates once you close your browser...)

Explanation:

0             % Push 0 on stack
T    % Start infinite loop
t_D         % Duplicate top element, negate and display (which consumes the duplicate)
QtD      % Add 1 to top of stack, duplicate and display (which consumes the duplicate)


# Rust, 39 bytes

||for i in 0..{print!(" {} {}",i,-1-i)}


This uses i32. adding i64 right behind the zero would make it use that instead at a cost of 3 more bytes. Rust has no bignum types in the standard library. When overflowing, this will either panic or quietly wrap around, depending on compiler options.

q KDB+, 25 bytes

n:-0W;while[n<0W;0N!n+:1]


Set n to negative infinity.

n:-0W


Increment and output n.

0N!n+:1


Loop until n < infinity.

n<0W


Possible alternate 17 bytes

(0N!1+)\[0W>;-0W]


Uses the \ (iterate) dyadic function to apply left hand side (plus 1 then output) from negative infinity (-0W) to infinity(0W).

Only problem is that it may throw a wsfull error eventually or at the very end after outputting all the integers.

# Brain-Flak, 28 + 3 = 31 bytes

To get a program that outputs every integer in some finite time (but the whole thing in infinite time) you need to use debug flags.

Try it online

(@dv()@dv){([[{}]@dv]()@dv)}


The program is 28 bytes and the command line flag is 3 making the total 31.

An alternative that does not technically fit the specs:

Try it online

(({})()){([([({})])]())}


If you run the program you will notice there is no output. This is because Brain-flak programs output when they terminate. It will output all the numbers at once once infinite time has elapsed. If you want to verify that it works try it online with debug flags.

# Java 8, 87 bytes

Alternative solution using an IntStream to iterate through all integers.

java.util.stream.IntStream.rangeClosed(1<<31,~1<<31).forEach(n->System.out.println(n));


## Alternative, 57 bytes

I didn't want to post this as my main answer, because it's just stolen from @KevinCruijssen's Java 7 answer, switched to go from negative to positive for no particular reason, and turned into a lambda. But it is technically shorter.

()->for(int i=1<<31;i<0;System.out.println(i+"\n"+~i++));


# JS (NON - ES6), 25 bytes

for(n=0;;)alert([~n,n++])


Uses binary NOT (~) for reverse sign and deincrement.

# Excel VBA, 25 20 Bytes

Anonymous VBE immediate window function that takes no input and outputs to the vbe immediate window

Do:?1-n;n:n=n+1:Loop


Note: Excel will appear to be non-responsive after executing to n=6012, adding a DoEvents: call at the beginning of any of the lines in the do...loop corrects this visual bug, but is not necessary for correct execution.

# 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)  »;


# Husk, 2 bytes

İZ


Try it online!

I know Husk is created after the post of the challenge but I think it is still worth mentioning.

# 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


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

## protected by Community♦Nov 20 '17 at 13:16

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