# 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
Commented Sep 16, 2016 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
Commented Sep 16, 2016 at 9:10
• @xnor Changed, though that kinds of ruins the very name of the challenge. Commented Sep 16, 2016 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. Commented Sep 16, 2016 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
Commented Sep 16, 2016 at 9:58

# 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

# cQuents, 7 bytes

=0:k,-k


Try it online!

Do you really need an explanation?

# Red, 37 bytes

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


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

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

# Julia, 24 bytes

f(n=0)=f(~n+(0>@show n))


Try it online!

# Vyxal5, 8 bytes

∞›(n,n⌐,


Explanation:

∞›(n,n⌐, # main program
∞›       # creates an infinite generator starting at 1
(      # iterates over it
n,    # prints the numbers [1, ∞)
n⌐, # prints the numbers (-∞, 0]


Mapping would be better, but currently mapping generator output is not optimal.

Try it Online!

# BRASCA, 20 18 bytes

-2 bytes thanks to RezNesX

nEo1[:nEo:0$-nEo}]  Try it online! ## Explanation (old) <implicit> - The stack has infinite zeroes at the bottom nEo - Print "0" and a space 1[a A] - Infinite loop: }:nEo - Print next positive integer and a space$         -   Swap to the negative number on the stack
{:nEo    -   Print next negative integer and a space
$- Swap back to the positive number on the stack  • 18 bytes: nEo1[:nEo:0$-nEo}] Commented May 12, 2021 at 11:13

# AWK, 33 32 bytes

This code prints all integers in one line:

BEGIN{for(ORS=FS;;)print -i++,i}


An alternative 33-byte answer, which prints one integer per line:

BEGIN{for(;;)print n+=i++*(-1)^i}


Try it online!

# GolfScript, 12 bytes

0{.p.~p).}do

0            # push 0 to the stack
{           # this block will execute at least once, even though the TOS is 0
.p         # print the current number
.~p      # print the bitwise NOT of the current number
)     # increments the current number
.}do # creates an infinite loop


Because the bitwise NOT of x = (-x - 1), as the number increments, the inverse decrements. The bitwise NOT of 0 is -1, therefore it can be trivially proven that all integers are counted exactly once.

I know there's already a (longer) GolfScript solution here, I apologise if this is breaking any rules.

# Kotlin, 49 48 bytes

(Int.MIN_VALUE..Int.MAX_VALUE).onEach(::println)


Saved one byte by using another iterator function

Try it online!

#### 49 bytes variant

(Int.MIN_VALUE..Int.MAX_VALUE).forEach(::println)


Try it online!

Expected output

-2147483648
-2147483647
-2147483646
...
-1
0
1
2
...
2147483645
2147483646
2147483647


The program will take a while since this is only a single threaded printing and integer values reach -2147483648 to 2147483647.

# Commodore C64 BASIC, 29 BASIC Bytes (does not end gracefully), 24 PETSCII characters with keyword abbreviations

0?i%,nO(i%),;:i%=i%+1:gO


By declaring a variable with a % identifier, you are telling Commodore BASIC to produce only integer representations of any floating point number, and this is within the range of -32768 to +32767 inclusive. The nO command, or NOT is a bitwise operator which may only be used with the same range previously mentioned (PRINT NOT (32768) for instance produces an ?ILLEGAL QUANTITY ERROR. Further reading about this is detailed here.

Because we are using line 0, we don't need to specify a line number with the GOTO command (at least not in BASIC 2.0 on the C64 and VIC-20; this may not be the same for all versions of Commodore BASIC).

The output is produced like:

 0 -1 1 -2

and will continue until the maximum range is met, and produce an error.

## With a graceful ending, 39 BASIC Bytes, 35 PETSCII characters with keyword abbreviations

0?i%,nO(i%),;:i%=i%+1:ifi%<32768then0


The same as above, but an IF condition is added. We can just use THEN0 rather than THEN GOTO 0 to save some typing.

# Fortran (GFortran), 34 bytes

i=0
1 i=i+1;print*,1-i,i;goto1;end


Boringly had to waste 4 bytes setting i=0 otherwise Fortran just initialises the variable to anything

Try it online!

## Commodore Basic, 18 bytes

1N=N+1:?N,1-N,:G┌1


PETSCII substitution: ┌ = SHIFT+O

Prints the sequence "1, 0, 2, -1, 3, -2...", with characters separated by tabs.

• Work up to the numbers with the biggest magnitude of the standard integer type? Yes. Commodore Basic integers have a range of -32768 to +32767; this program uses 40-bit floats with a 32-bit mantissa, and can print any number between -999999999 and 999999999.
• Output in decimal? Yes. Integers stored in a floating-point number are printed as integers as long as they are nine digits or less.
• Each integer separated from the next using any separator? Yes. There is always a tab character between two integers.
• The separator must not change? Yes. The separator is always exactly one tab character.
• The separator can consist of multiple characters, as long as none of them is a digit nor the negative sign? Yes. A tab character is neither a digit nor a negative sign.
• Any supported integer must eventually be printed after a finite amount of time? Yes. After about 25 minutes, it'll print the sequence 32767 -32766 32768 -32767 32769 -32768, finishing out the set of Commodore Basic-supported integers.
• Seems invalid: "The separator must not change at any point." Commented Sep 17, 2016 at 8:09
• @primo, better now?
– Mark
Commented Sep 17, 2016 at 16:47
• Commodore Integers have a range of -32768 to +32767 in BASIC, so this breaks this rule: Your program has to work up to the numbers with the biggest magnitude of the standard integer type of your language. - if you change the variable to N%, this may be slower, but it will work, though it will error if it exceeds either the range. Commented Jun 6, 2023 at 16:46
• @ShaunBebbington, my program works well beyond the range of standard integers. N is a 40-bit floating-point variable, with a 32-bit mantissa and 8-bit exponent. It can store any integer between -999999999 and 999999999 with complete accuracy.
– Mark
Commented Jun 6, 2023 at 20:59
• And yes, floats are the natural way of storing integers in Commodore Basic. They've got a wider range than integers, they're every bit as fast (all arithmetic is done using floating point, regardless of the underlying type), and the variable names are easier to type. The only time you'd use N% over N is if you're strongly memory-constrained.
– Mark
Commented Jun 6, 2023 at 21:01

# C, 64 58 Bytes

Thanks to @12431234123412341234123

f(n){printf(",%d,-%d",n,n);f(++n);}main(){f(printf("0"));}


Try it online!

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

• Combine both, positive and negative, numbers in a single printf() makes it shorter: f(n){printf(",%d,-%d",n,n);f(++n);}main(){f(printf("0"));} Alternative (same length): f(i){printf(" -%d%*s%d",i,!!i,"",i);f(i+1);} main(){f(0);} Commented Jul 18, 2023 at 13:27

# Uiua, 18 bytes

⍥(+⟜⊃±∵&s)∞¯1_1&s0


Explanation:

  ⍥(+⟜⊃±∵&s)∞¯1_1&s0
# ^ ^ ^^^   ^^   ^
# | | |||   ||   └- print 0
# | | |||   |└----- [-1 1]
# | | |||   └------ do infinitely
# | | ||└---------- print each
# | | |└----------- sign of elements
# | | └------------ fork both functions
# | └-------------- increment by sign
# └---------------- repeat until


# Swift 5.9, 32 bytes

(0...).map{print($0) print(~$0)}


I tried desperately to merge the two calls to print(_:separator:terminator:) into one, but the fact that terminator is a newline by default seriously complicates things.

# 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) Commented Sep 16, 2016 at 13:39
• Non-wrapping can be shorter by printing before decrementing: +[.+>.-<] Commented Sep 16, 2016 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++ 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. # 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))) Commented Mar 29, 2018 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.

# 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.
– user45941
Commented Sep 26, 2016 at 6:40

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