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

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

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

# 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) Sep 16, 2016 at 13:39
• Non-wrapping can be shorter by printing before decrementing: +[.+>.-<] 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, 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) Sep 16, 2016 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, 2016 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. Sep 16, 2017 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. May 6, 2020 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. # 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))) 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
Sep 26, 2016 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. Sep 17, 2016 at 15:53
• That loop doesn't print a delimiter between the numbers. Oct 13, 2016 at 23:08
• C++ implicitly returns 0 from main, so you can ditch the whole return 0; for -9 bytes, also the space in #include <iostream> is not required
– c--
Jun 28, 2022 at 15:48

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

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

# Visual Basic .NET (Mono), 95 bytes

A declared subroutine that takes no input and outputs to the console.

Module M
Sub Main
Dim i
Do
Console.WriteLine(-i &IIf(i," "&i,""))
i=i+1
Loop
End Sub
End Module


Try it online!

# F#, 69 bytes

let f=
let mutable i=0m
while 1>0 do
printf"%O,-%O,"i i
i<-i+1m


It's pretty straight forward. The 0m sets i as 0, but of type decimal. Since we're allowed to print 0, -0 I'm doing that. i gets incremented with every iteration of the loop, and the value is printed out.

I my initial idea would have been 70 bytes but (like most of my initial ideas) it would never have worked:

let g=Seq.iter(fun x->printfn"%O,-%O"x x)[0m..System.Decimal.MaxValue]


In this one [0m..System.Decimal.MaxValue] creates an array starting at 0, adding 1 each time and going all the way to the maximum decimal value. (Another example would be the expression [1..10] creates an array with {1,2,3,4,5,6,7,8,9,10}).

Seq.iter would then apply the function for printing to that array.

The problem with this is that the array must be constructed before iterating through it. So for all integers, with infinite memory the array could be constructed - but it would also take an infinite amount of time, so nothing would ever be printed out!

# Javascript, 96 bytes

f=n=>f([].concat(...n.map(i=>alert(+i?i+' -'+i:i)||+i?y.map(o=>i+o):[])));f(y=[...0123456789])


Alerts all integers in the sequence (0, 1, -1, 2, -2, ...), using strings to go beyond JS's usual max safe integer 9007199254740991. This is equivalent to the "Infinite version" in Arnauld's earlier answer.

# Scala, 112 bytes

val x=Int.MaxValue
val y=Int.MinValue
print(0)
for(a <-1 until x) print(","+a + "," + a * -1)
print(","+x+","+y)


Try it online!

# Scala, 143 bytes

object ListNumbers extends App {
val x = 10
val y = -10
print(0)
for(a <- 1 until x) print(","+a + "," + a * -1)
print(","+x+","+y)
}


Try it online!

# Using Java 8 Streams just for fun, it generates a lazy populated string

types declarations can be omitted but I included for "documentation"

# Scala, 253 bytes

val zero :Stream[String] = Stream("0")
val positive :Stream[Int]= Stream.from(1)
val negative :Stream[Int]= positive.map(_* -1)

val stream = zero ++ positive.zip(negative).map(x => x._1.toString()+","+x._2.toString())
//stream.take(Int.MaxValue).toList


Try it online!

• 44 bytes. Probably could go down more Apr 27, 2020 at 18:39