# 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

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

# Jelly, 5 bytes

Ṅ~ṄNß

Try it online!

### How it works

Ṅ~ṄNß  Main link. Argument: n. Implict argument: 0

Ṅ      Print n and a linefeed.
~     Apply bitwise NOT, yielding -(n + 1).
Ṅ    Print -(n + 1) and a linefeed.
N   Negate, yielding n + 1.
ß  Recursively call the main link with argument n + 1.

# SQL, 84 76 Bytes

Saved 8 Bytes thanks to steenbergh :)

Golfed:

DECLARE @n INT SET @n= 1 WHILE 1=1 BEGIN PRINT 1-@n PRINT @n SET @n=@n+1 END

Ungolfed:

DECLARE @n INT
SET @n= 1
WHILE 1=1
BEGIN
PRINT 1-@n
PRINT @n
SET @n=@n+1
END

Prints:

0
1
-1
2
-2
3
-3
4
-4
5
-5
...
• Using the 1-n trick you can drop the PRINT 0 at the start of your function: DECLARE @n INT = 1 WHILE 1=1 BEGIN PRINT 1-@n PRINT @n SET @n=@n+1 END Nov 11 '16 at 9:54
• @steenbergh Cool, thanks! It wouldn't let me declare and set on the same line, but still saved 8 Bytes! :) Nov 11 '16 at 17:41
• Nice answer. FYI the DECLARE trick @steenbergh mentioned is version specific; it works only in SQL 2008 and later. SQL 2008 also added the @+=1 "compound" operator, which saves 2 bytes over @=@+1. You can use @ instead of @n for the variable; its weird but works. Finally, a label like A: with GOTO A is shorter than a WHILE loop. All that can bring it down to 49: DECLARE @ INT=1A:PRINT 1-@ PRINT @ SET @+=1GOTO A Apr 27 '20 at 19:26

# Pyke, 7 2 bytes

~I

Try it here!

### 7 bytes

oDID_)r

Try it here!

If printing +-0 is ok, oD_r

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

# MarioLANG, 17 bytes

:<
+"
)(
-:
>!
=#

Try it online!

Vertical loops are normally shorter in MarioLANG. This outputs:

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

# C (gcc), 40 38 36 bytes

main(i){for(;printf("%d ",i),i++;);}

Try it online!

### Explanation:

The first argument to main() is argc, which is 1 if the program is run without additional parameters. When we reach the max positive integer, i wraps around and becomes negative. The program stops when i==0, after printing it.

Thanks @ceilingcat for -3 bytes

• You can save 4 bytes by {while(i)printf("%d ",i++);} Apr 6 '17 at 19:13
• But then it would not print 0 at the end.
– G B
Apr 7 '17 at 7:14
• Your answer inspired me to try recursion! Saves one byte, but at the cost of ugliness and undefined behavior: main(i){printf("%d ",i,i++&&main(i));}
– Josh
Oct 3 '19 at 19:59
• This doesn't print negative integers
– Jo King
Nov 21 '19 at 5:49
• You are right, I rolled back to the non-recursive version (which was in fact 1 byte shorter than I previously thought).
– G B
Nov 21 '19 at 6:48

# Pyth, 6 bytes

0f!
_

Try it online!

In string representation, this is "0f!\n_\n".

We print 0 explicitly, then use f in "count up from 1 until result truthy" mode, where the function prints the input, negates it, prints that, and then boolean negates the result so f will never halt.

## PowerShell v2+, 26 bytes

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

### Truly infinite, 34 bytes

0;for([bigint]$i=1;;$i+=1){$i;-$i}

For a truly infinite variation that will (eventually) print every single integer in existence given infinite time and memory, try the above. We simply tack on the [bigint] cast and change slightly how the loop is calculated.

# ><>, 11 bytes

lnao0l-naol

Try it online! Uses the stack length as a counter.

ln             Output length of stack
ao           Output newline
0l-n       Output 0 - (length of stack + 1), +1 because of the additional 0
ao     Output newline
l    Push length of stack, increasing the stack length by 1
(Implicit loop since ><> is toroidal)

# Vim, 19 keystrokes

i0<cr>1<esc>qqYpi-<esc>p<C-a>@qq@q

Creates a recursive macro that duplicates a number, makes it negative, prints the original number again and increments it.

# Hexagony, 22 18 bytes

!(~2016}Q2;'Oct4!~

Try it Online!

Excuse me for keep editing.. After typing the explanations I managed to squeeze.. not so squeeze this into a 3-hexagon and there are still plenty of space to put today's date in.

I have a love at first sight with this language...

!(._/;'<~.2/~/!}Q/>.$> ## Expanded ! ( . _ When n<=0, print (-ve number) and n-- / ; ' < ~ After printing , . 2 / ~ / ! If n<=0, n=-n and print (the +ve number) } Q / > .$ >     Else n=-n and go into auto-if
. . . . . .
. . . . .
. . . .        When n>0, do nothing as the number is printed at line 3

The basic algorithm is,

Loop: print, if(n<=0) n--, n=-n, then print ,

I come into this answer with the thought of using implicit if by going out of the corner:

! ( . .
. . . . .
. . . . . .
. ~ } Q 2 ; '
. . . . . .
. . . . .
! . . .

However it is real using a lot of bytes for no-ops in putting the ! there, and in the hope of getting the ! (print) back into the main middle loop, I found it hard to print the 0 since the if(n<=0)n-- is run before the main loop for printing. So keep drawing on a whiteboard (it is easier to overwrite a byte on a whiteboard than most of other tools) I came up with the above which puts one extra ~ (negation) after branching at line 2 but saves me from using the no-ops at the end.

Anyone who can guide me how to make beautiful Hexagony explanation images?

## Wumpus, 8 bytes

=nON
=)N

Try it online!

Prints the integers in the order -1, 0, -2, 1, -3, 2, ... using linefeed separation.

### Explanation

Let's look at the actual grid first:

The instruction pointer starts in the top left corner moving east and will reflect off the edge whenever it reaches a boundary of the code. Hence, this program loops through the code indefinitely, but we reuse the single O (because it's executed both before and after entering the top right corner).

So the loop body looks like this:

=nONON)=

Let's go through this:

=   Duplicate the top of the stack. Initially, this is an implicit zero,
but in general this will be the non-negative number of each pair we print.
n   Bitwise NOT. Turns the copy of n into -n-1.
O   Output -n-1.
N   Output a linefeed.
O   Output n.
N   Output a linefeed.
)   Increment n to n+1.
=   Duplicate it (because one copy of it will be printed in the next iteration).
• Figured out a one liner in the same amount of bytes. Try it online!
– Jo King
Feb 12 '18 at 2:16
• @JoKing neat! :) Feb 12 '18 at 6:38

# Prolog (SWI), 33+3 = 36 bytes

A*B:-C is B-A,writeln(C),C*(1-B).

Try it online!

Called as 0*0.

Prints 0, 1, -1, 2, -2 ... separated by newlines.

Saved 5 bytes thanks to SQB
Saved 16 bytes thanks to user3744156

• You can shave off a couple of bytes by leaving out the p:-0*1 and calling it as 0*1 instead. You'd have to count those 3 bytes, I think.
– SQB
Sep 17 '16 at 18:19
• @SQB: Do you have a meta on that? That sounds akin to requiring a program to take a specific input in order to work, which sounds like a questionable practice to me. Sep 18 '16 at 8:16
• No I don't, but I once got a similar comment on an entry in prolog. It does make some sense, though, or one could offload the byte count to the call.
– SQB
Sep 18 '16 at 8:21
• Great entry, by the way. I'm a bit puzzled why the combination of writeln/1 and plain write/1 works the way it does, but... it does!
– SQB
Sep 18 '16 at 8:23
• @SQB I suppose that makes sense for Prolog if, as you say we add the query to the byte count. I'm not sure either why writeln writes on a newline before it does nl. That's not the way it usually works in most languages. Sep 18 '16 at 12:08

# Hexagony, 14 bytes

Compacted:

!~{/")!;/;"~{/

Formatted:

! ~ {
/ " ) !
; / ; " ~
{ / . .
. . .

Try it online!

Improves upon @Sunny Pun's answer by not using the middle -> edge branches, but instead uses a more linear control flow, while delimiting with null bytes (didn't see anything against this) which are the default state of memory in Hexagony.

# Dyalog APL, 18171514 12 bytes

{∇-⎕←1-⎕←⍵}0

Try it online!

{       Begin function
∇     Call recursively with new argument and repeat: -⍵-1
-     Negate sign to make it negative again: -⍵-1
⎕←    Print current value: ⍵+1
1-    Subtract it from 1, flipping the sign and incrementing the absolute value: ⍵+1
⎕←    Print current value: -⍵
-     Negate sign to make it negative: -⍵
⍵     Argument to function, starts at 0 and increments by one each time: ⍵
}       End function
0       Call function with 0

Thanks to @Razetime & @Adám for their help golfing my original 18 bytes to 12. It started as ⎕←0⋄{∇⊃1+|⎕←-⎕←⍵}1 and is far more elegant now, not to mention more competitive!

## Befunge 93, 8 bytes

:.-:0!-

Try it online!

### Explanation

Befunge's stack is thankfully filled with an implicit infinite amount of zeros, and printing a number also prints a trailing space.

:.    Print the top of the stack.
-     Subtract it from the implicit zero underneath, effectively multiplying by -1.
:0   Check whether its greater than 0.
!     Logical NOT. Gives 0 if the current value is positive and 1 otherwise.
-     Subtract from current value.

The source code is toroidal so this program repeats indefinitely.

# Lua , 43 Bytes

i=1;while 1 do print(1-i);print(i);i=i+1 end

# Perl, 19 bytes

perl -E 'say-$}while say$}++'

In reality will get stuck when at some huge number $} switched to floating point and starts losing precision. This 27 byte version will really print forever: perl -E 's//0/;say"-".++$_ while say'
• Nice. say"-".++$_ while say$_|0 should behave as your second solution if I'm not mistaken, and is 2 bytes shorter.
Sep 16 '16 at 16:40
• Your version has the same problem as my first version: Once $_ gets big enough precission will freeze it. The essence of my second version is that$_ always contains a pure string representation of the number in which case perl will apply magic increment. Notice also that "-".++$_ is needed, -++$ would convert $_ back to a number. Replace s//0/ by$_=9x99 to see it in action Sep 16 '16 at 16:53
• Ok, got it. I was trying to figure out why the second version was working while the first wasn't (more or less), thanks for the explanations.
Sep 16 '16 at 16:59

# C# 222 bytes (Infinite output version)

Being more fond of the infinite output version of the print-all-integers program, I created this.

IEnumerable<string>g(){var w=new[]{'0'};yield return "0";while(true){var c=true;for (var r=w.Length-1;c&&r>=0;r--)if(c=++w[r]==58)w[r]='0';var b=new string(w);if(c)w=(b="1"+b).ToArray();yield return b;yield return "-"+b;}}

This function continuously returns the next greater positive and negative integers. The values are not limited by the integer type but since integers are used to handle the array, the program will fail when the number has more than 2,147,483,647 digits. However, it will most likely run out of memory long before that happens.

Usage:

static void Main(string[] args)
{
foreach (var n in g())
{
Console.WriteLine(n);
}
}

## Retina, 21 19 bytes

{M*.
^
1
*.+
-$.& Try it online! (Takes about a minute before you see anything.) ## Burlesque, 12 bytes 0R@J-1?*_+[- You can try a restricted version here. 0R@ Range from 0 to Infinity J Duplicate -1?* Multiply one Block by -1 (negative integeres) _+ Concatenate [- Tail to Remove the duplicate zero ### 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! # Java, 49 bytes o->{for(int n=1<<31;n<0;)o.println(n+"\n"+~n++);} Notes: • o is a java.io.PrintStream but its import is not required given it's the parameter of a lambda expression. • This must be run on a Unix machine to properly use the same separator. ## Ungolfed import java.io.PrintStream; import java.util.function.Consumer; public class Main { public static void main(String[] args) { Consumer<PrintStream> func = o -> { // define the output and start the function. for (int n = 1 << 31; n < 0; n++) { // for each negative integer increasing from Integer.MIN_VALUE o.println(n + "\n" + ~n); // Print the negative number and its complement to 2 value. } }; func.accept(System.out); } } ## Result -2147483648 2147483647 -2147483647 2147483646 -2147483646 2147483645 -2147483645 2147483644 -2147483644 2147483643 -2147483643 2147483642 -2147483642 2147483641 -2147483641 2147483640 ... -7 6 -6 5 -5 4 -4 3 -3 2 -2 1 -1 0 # R, 33 29 bytes x=0;while(T)cat("",-x,x<-x+1) # Output (for < 10) 0 1 -1 2 -2 3 -3 4 -4 5 -5 6 -6 7 -7 8 -8 9 -9 10 # Explanation It works because x is set to 0, then prints -0 which displays as 0. It then increments and prints that, giving 1. The next element is the negative value of the last which is -1 and so on... EDIT: Cut it down by 4 bytes after I realised that I could just have it loop forever. In R, T is TRUE by default. • Hi, welcome to PPCG! Hmm, I've never programmed in R before, so correct me if I'm wrong, but doesn't this print 0 two times in the following sequence 0, 0, -1, 1, ...? Sep 19 '16 at 13:06 • It doesn't because it prints -0 (which prints as 0) then increments by 1 and prints that. An example of the output for x<10: 0 1 -1 2 -2 3 -3 4 -4 5 -5 6 -6 7 -7 8 -8 9 -9 10 Sep 19 '16 at 14:53 • Ah ok, thanks for clarifying and adding the explanation. I was asking because I made a similar mistake with my own answer before, which printed 0 and -0 (second 0). Like I said, I never used R myself, so I knew there was a small chance I just didn't fully understand the code. +1 from me, and once again welcome. Sep 19 '16 at 15:02 # PHP, 28 27 bytes for(;1;)echo 1-++$i," $i "; As aross pointed out in the comments this only outputs PHP_INT_MIN (or indeed PHP_INT_MIN + 1) on a 32 bit implementation of php. Old versions: for(;++$i;)echo 1-$i,"$i ";

If a leading space is allowed then

for(;++$i;)echo"$i ",1-$i; Is 1 byte shorter. (same length as new version) • This won't output PHP_INT_MIN, so it's invalid Sep 26 '16 at 8:23 • sure it will, it switches over to a double representation which has enough precision to be accurate to php_int_min. Sep 26 '16 at 8:53 • No it won't. Just set$i to a high number and let it run from there to see for yourself. It will output -9.2233720368548E+18 9.2233720368548E+18 (and will continue to output this for eternity). Adding 1 will not change the value of the float due to lack of precision. The last INTs in the output are -9223372036854775806 9223372036854775807 Sep 26 '16 at 8:59
• ah, maybe i should have been more precise: it will if you run it on a 32 bit version of php, such as php 5.6 on windows. where php_int_max is 2147483647 Sep 26 '16 at 9:34
• So your answer is only valid in a very specific system, and you should note that Sep 26 '16 at 9:40

# PHP, 24 26 bytes

(24 bytes not displaying PHP_INT_MIN)

for(;;)echo-$i++,"$i ";

Output : 0 1 -1 2 -2 3 -3 4 -4 5 -5 6 -6 7 -7 8 -8 9 -9 10 -10 ...

# Tweaks

• Use binary negation instead of xor with -1. Requires another cast to int to handle the null case. Saved a byte.

# LI, 16 7 bytes

New solution:

R-0P-1P

I feel kinda silly for not realizing I could have done this before. I'm keeping the other one because it shows off more flow control and more functions.

LI is a (very) WIP language that relies primarily on recursion. Every program in LI must take in user-provided input, so the given program here accepts LI's "null" input of 0.

The current Python interpreter is just barely enough to meet the specifications of this challenge, albeit wordy; I'm working on a Racket interpreter that would be able to meet the specs of this challenge with three bytes, but unfortunately it's not even close to challenge-ready.

Explanation:

P    Print input
-1     (1 - input)
P       Print that too
-0        (- (1 - input))
R          Rerun program with new input

Old solution:

R?>0i-0PyPi-0PYP

Roughly, this program translates to:

R                        Recurse program with input:
P        print-return (implicit input)
Y         Increment input
P          Print incremented
-0           Invert sign
= -(i+1)
?>0i                   if i is not negative.
-0PyPi            If i is negative, do the same but decrement (y) instead of increment.

For both solutions, output is of the following format:

0
1
-1
2
-2
3
-3
...

The default interpreter will run out of memory at -3338 (3342 with the new solution), if you're curious.

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.

## Powershell, 26 19 Bytes

for(){($b++);$b*-1}

updated because I should have done it months ago.

very straightforward, takes a variable $a, initializes as 0, then initiates an infinite loop with while(1){} and then displays the current value$a - increments it $a++ and displays the negative version of it$a*-1

output is automatically on a new line for each display, so the resulting output is:

0
-1
1
-2
2
-3
3
-4
• Nice to see another PowerShell golfer around! You could swap the while for a for, change how $b is initialized by encapsulating it in parens to place a copy on the pipeline, and turn$b*-1 into -$b. That gets you down to 17 -- for(){($b++);-\$b} ... outputs 0 -1 1 -2 2... with newlines in between. Oct 7 '16 at 18:51
• didn't realize you could use a blank for - thought you needed to use for(;;) which is the same bytes as while() - thanks for the tips! Oct 8 '16 at 13:53